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!!
3 Answers 3
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.
Comments
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
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.
[31312, 123213]a single response and are you getting three responses. Can you please explain the problem further