Ccna final exam - java, php, javascript, ios, cshap all in one. This is a collaboratively edited question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
Tuesday, May 1, 2012
How to flatten array in jQuery?
How to simply flatten array in jQuery? I have: [1, 2, [3, 4], [5, 6], 7] And want: [1, 2, 3, 4, 5, 6, 7]
callback( value, indexOrKey )The function to process each item against. The first argument to the function is the value; the second argument is the index or key of the array or object property. The function can return any value to add to the array. A returned array will be flattened into the resulting array. Within the function, this refers to the global (window) object.
You can use jQuery.map, which is the way to go if you have the jQuery Library already loaded.
ReplyDelete$.map( [1, 2, [3, 4], [5, 6], 7], function(n){
return n;
});
Returns
[1, 2, 3, 4, 5, 6, 7]
Use the power of JavaScript:
ReplyDeletevar a = [[1, 2], 3, [4, 5]];
console.log( Array.prototype.concat.apply([], a) );
//will output [1, 2, 3, 4, 5]
var a = [1, 2, [3, 4], [5, [6, [7, 8]]]];
ReplyDeletevar b = [];
function flatten(e,b){
if(typeof e.length != "undefined")
{
for (var i=0;i<e.length;i++)
{
flatten(e[i],b);
}
}
else
{
b.push(e);
}
}
flatten(a,b);
console.log(b);
The flatten function should do it, and this doesn't require jQuery. Just copy all of this into Firebug and run it.
You can use jQuery.map():
ReplyDeletecallback( value, indexOrKey )The function to process each item
against. The first argument to the function is the value; the second
argument is the index or key of the array or object property. The
function can return any value to add to the array. A returned array
will be flattened into the resulting array. Within the function, this
refers to the global (window) object.