0

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

4
  • I'm curious as to why you're executing an anonymous function in the middle of an array definition... Commented Nov 17, 2015 at 20:53
  • 1
    var arr = ['a','b','c','d']; ? Commented Nov 17, 2015 at 20:53
  • 1
    What are you trying to accomplish exactly? Commented Nov 17, 2015 at 20:53
  • The array definition builds up a collection of complex objects which a third party component uses to display a dialog. The function will be a utility method that is used in lots of places, I made it an anonymous function for brevity, ill edit the example. Commented Nov 17, 2015 at 20:56

3 Answers 3

2

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');
Sign up to request clarification or add additional context in comments.

3 Comments

@SzabolcsPáll I am assuming that OP doesn't want to create an array with 4 constants in it. They probably want to generate values to insert into the array dynamically, and just created an example with constants...
I can't (easily) do it the second way because this is within a very large block of json. The first way will work well though, thanks.
Why not [].concat('a',function(){return ['b','c'];}(),'d'); ?
2

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

1 Comment

Interesting approach (I'd forgotten about reduce) but I'd imagine a single straight concat would be faster/less code.
0

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

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.