0
var a=[{"id":1, "name":"aaa", "age":31}, {"id":2, "name":"bbb", "age":23}, {"id":3, "name":"ccc", "age":24}]

var b=[{"id":4, "name":"ddd", "age":43}]

var result=[{"id":1, "name":"aaa", "age":31}, {"id":2, "name":"bbb", "age":23}, {"id":3, "name":"ccc", "age":24}, {"id":4, "name":"ddd", "age":43}]

I want to insert b into an index of 3. anybody know this one?

1

6 Answers 6

1
var result = a;
result.push(b[0]);
Sign up to request clarification or add additional context in comments.

2 Comments

good call, though it only works when there is only 1 item in b
Yeah you can use apply() or call() method but OP hasn't mentioned that so I just answered that...
1

a.push.apply(a, b)

This will call the Array's push method with as many arguments as there are items on b, that is to say a.push(b[0], b[1], b[2], ...)

Plain JS, no jQuery needed :)

PS: Note this modifies a. If you don't want this, then you can first clone it with Array.slice :

var result = a.slice(); 
result.push.apply(this, b);

Comments

1

Good practice is

a[a.length] = b;

Here a.length is 3 that means next(or last) index to insert the data.

Comments

0

Please check the below code

var result = a.concat(b);

3 Comments

this won't produce the result the PR expects, he'll have an array as the last item in a instead (b being an array)
@Greg Concat function will concat two arrays and create a new array
Actually you're right @sameer, if the goal is not to modify a this is a good answer.
0

Please check with the below code.

var a=[{"id": 1, "name":"aaa","age":31},{"id": 2, "name":"bbb","age":23},{"id": 3,name:"ccc","age":24}]
var b=[{"id": 4, "name":"ddd","age":43}];
function insertInto(index, a, b){
    var x = a.splice(index);
    a = a.concat(b);
    a = a.concat(x);
    retrun a;
}
a = insertInto(2,a,b);

Comments

0

Please check below code

var a = [{ "id": 1, "name": "aaa", "age": 31 }, { "id": 2, "name": "bbb", "age": 23 }, { "id": 3, "name": "ccc", "age": 24}];
        var b = [{ "id": 4, name: "ddd", "age": 43}];
        var result = a.concat(b);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.