Reputation: 645
I'm creating an array using "push"
so the result is [Object, Object]
in there the code looks like:
[Object, Object]
0: Object
type: Array[6]
1: Object
type: Array[4]
I would like to combine both object and get a result like this:
["Mike", "Matt", "Nancy", "Adam", "Jenny", "Carl", "Jim", "Issac", "Lee", "Won"]
I have no idea to get this to work, any suggestion?
code sample:
dropdown: function(data) {
var arr = [];
$.each(data, function(key, value) {
arr.push({
type: value.type
});
});
}
Upvotes: 1
Views: 61
Reputation: 83358
You can concatenate one array onto another with concat.
arr = arr.concat(otherArr);
Note that concat
creates a new array, leaving the original unchanged, which is why you have to re-assign it.
Note - for three arrays, you can just keep passing them in.
var arr1 = [0,1];
var arr2 = [2,3];
var arr3 = [4,5];
arr1 = arr1.concat(arr2, arr3);
console.log(arr1);
EDIT
You mentioned having dynamic arrays. I'm not sure what you mean by that, but I'll note that if you have an arbitrary array of arrays, and you want them all concated, you can do this
var arr1 = [0,1];
var arr2 = [2,3];
var arr3 = [4,5];
var otherArrays = [arr2, arr3];
arr1 = Array.prototype.concat.apply(arr1, otherArrays);
console.log(arr1);
Upvotes: 4
Reputation: 780798
A simple loop:
var result = [];
for (var i = 0; i < objects.length; i++) {
$.merge(result, object[i].type);
}
Upvotes: 0
Reputation: 7416
Use concat
, like this
arr1=["apple","orange","pineapple","pomegranate"];
arr2=["pizza","candy","chocolate","tasty"];
arr3=["food","drink"];
concatted=arr1.concat(arr2).concat(arr3);
You can keep chaining together arrays like that for as long as you want, until you run out of memory
Alternatively, you can just do this
concatted=arr1.concat(arr2,arr3);
If you want to remove duplicates, you can use this
Array.prototype.removeDuplicates=function(){
var newArray=[];
for(var i=0;i<this.length;i++){
if(newArray.indexOf(this[i])==-1){
newArray.push(this[i]);
}
}
return newArray;
}
Upvotes: 1
Reputation: 9262
Since you specified that you can use jquery, check out the merge()
function: http://api.jquery.com/jquery.merge/
Upvotes: 0