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!!

asked Jan 8, 2016 at 4:14
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.

answered Jan 8, 2016 at 4:15
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>

answered Jan 8, 2016 at 4:21

Comments

1
answered Jan 8, 2016 at 4:17

1 Comment

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.