2

Before all, sorry for my english

I am trying to save multiples web responses into an array

I have something like this:

var array = [];

$.ajax({
    url: URL,
    success: function(e){
        array.push(e);
    }
});

But i get anything like this:

[[31312, 123213], [12321, 123123], [123213, 132132]]

And i want to get:

[321321, 321321, 32131, 321312, 321321, 321312]

How i can do this?

Thanks in advance!!

1
  • is [31312, 123213] a single response and are you getting three responses. Can you please explain the problem further Commented Jan 8, 2016 at 4:26

3 Answers 3

5

Replace

array.push(e);

with

array.push.apply(array, e);

If e is e.g. 1, 2, 3, the first one will execute array.push([1, 2, 3]), while the second will execute array.push(1, 2, 3), which gives you the correct result.

Sign up to request clarification or add additional context in comments.

Comments

2

You can use a recursive function to flatten the multidimensional array into a single flat one.

var data = [[31312, 123213], [12321, 123123], [123213, 132132]]

function flatten( arr ){
  return arr.reduce(function( ret, item ){
    return ret.concat( item.constructor === Array ? flatten( item ) : [ item ] );
  }, [])  
}

console.log( flatten( data ) );
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>

Comments

1

You can use concat

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

array = array.concat(e)

1 Comment

concat is slightly less efficient than push, as it will copy the array in each iteration. It will work, though.

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.