简体   繁体   中英

Add multiple elements to an array from a function called within the array?

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

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');

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>'); 

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, ie:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM