Reputation: 1425
This is probably a very simple question and has probably been answered before but I've researched it and I can't find anything. If I run the following code:
function addElements(arg1,arg2){
return ['b','c'];
}
var arr = ['a',addElements('foo','bar'),'d'];
alert(JSON.stringify(arr));
Then I get an array like this:
['a',['b','c'],'d']
how can I make it create a single dimensional array like this
['a','b','c','d']
Thanks,
Joe
Upvotes: 0
Views: 52
Reputation: 386560
You can use Array.prototype.reduce()
The
reduce()
method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.
in combination with Array.prototype.concat()
The
concat()
method returns a new array comprised of the array on which it is called joined with the array(s) and/or value(s) provided as arguments.
var arr = ['a', function () { return ['b', 'c']; }(), 'd'],
arr2 = arr.reduce(function (r, a) {
return r.concat(a);
}, []);
document.write('<pre>' + JSON.stringify(arr2, 0, 4) + '</pre>');
Or use Array.prototype.map()
The
map()
method creates a new array with the results of calling a provided function on every element in this array.
var arr = ['a', function () { return ['b', 'c']; }(), 'd'],
arr2 = [];
arr.map(function (a) {
arr2 = arr2.concat(a);
});
document.write('<pre>' + JSON.stringify(arr2, 0, 4) + '</pre>');
Upvotes: 2
Reputation: 742
I assume you are asking a general solution for a data structure that can contains array inside array, and you want to flatten it.
You basically need a recursive method to do so if that the case, i.e.:
function flattenArr(arr) {
var outArr = [];
for (var i = 0; i < arr.length; ++i) {
if (Array.isArray(arr[i])) {
outArr = outArr.concat(flattenArr(arr[i]));
} else {
outArr.push(arr[i]);
}
}
return outArr;
}
Upvotes: 0
Reputation: 13409
If you insist on keeping this format, you can use concat
:
var arr = ['a'].concat(function(){
return ['b','c'];
}(), 'd');
alert(JSON.stringify(arr));
A cleaner approach and explanation:
// initial array
var arr = ['a'];
// use your function to add data to array
arr = arr.concat(function(){
return ['b','c'];
}());
// add more values
arr.push('d');
Upvotes: 2