Cómo aplanar matriz en jQuery?
¿Cómo simplemente aplanar una matriz en jQuery? Tengo:
[1, 2, [3, 4], [5, 6], 7]
Y quiero:
[1, 2, 3, 4, 5, 6, 7]
9 answers
Puede usar jQuery.map, que es el camino a seguir si tiene la biblioteca jQuery ya cargada.
$.map( [1, 2, [3, 4], [5, 6], 7], function(n){
return n;
});
Devuelve
[1, 2, 3, 4, 5, 6, 7]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-24 11:43:10
Usa el poder de JavaScript:
var a = [[1, 2], 3, [4, 5]];
console.log( Array.prototype.concat.apply([], a) );
//will output [1, 2, 3, 4, 5]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-24 12:03:44
Así es como puedes usar jquery para aplanar arrays profundamente anidados:
$.map([1, 2, [3, 4], [5, [6, [7, 8]]]], function recurs(n) {
return ($.isArray(n) ? $.map(n, recurs): n);
});
Devuelve:
[1, 2, 3, 4, 5, 6, 7, 8]
Aprovecha jQuery.map así como jQuery.isArray .
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-08 15:47:08
var a = [1, 2, [3, 4], [5, [6, [7, 8]]]];
var 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);
La función aplanar debería hacerlo, y esto no requiere jQuery. Solo copia todo esto en Firebug y ejecútalo.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-24 11:49:15
Para aplanar recursivamente un array puede usar el Array nativo .reducir la función. No es necesario usar jQuery para eso.
function flatten(arr) {
return arr.reduce(function flatten(res, a) {
Array.isArray(a) ? a.reduce(flatten, res) : res.push(a);
return res;
}, []);
}
Ejecutando
flatten([1, 2, [3, 4, [5, 6]]])
Devuelve
[ 1, 2, 3, 4, 5, 6 ]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-04 11:41:41
Puede utilizar jQuery.map()
:
Callback (value, indexOrKey )La función para procesar cada elemento contra. El primer argumento de la función es el valor; el segundo el argumento es el índice o clave de la propiedad array u objeto. El la función puede devolver cualquier valor para agregar a la matriz. Una matriz devuelta se aplanará en el array resultante . Dentro de la función, este se refiere al objeto global (ventana).
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-24 11:49:03
Puede usar Array.prototype.reduce
que técnicamente no es jQuery, pero ES5 válido:
var multidimensionArray = [1, 2, [3, 4], [5, 6], 7];
var initialValue = [];
var flattened = multidimensionArray.reduce(function(accumulator, current) {
return accumulator.concat(current);
}, initialValue);
console.log(flattened);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-22 09:39:39
Vieja pregunta, lo sé, pero...
Encontré que esto funciona, y es rápido:
function flatten (arr) {
b = Array.prototype.concat.apply([], arr);
if (b.length != arr.length) {
b = flatten(b);
};
return b;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-28 02:13:45
Use recursión si tiene varios niveles:
flaten = function(flatened, arr) {
for(var i=0;i<arr.length;i++) {
if (typeof arr[i]!="object") {
flatened.push(arr[i]);
}
else {
flaten(flatened,arr[i]);
}
}
return;
}
a=[1,[4,2],[2,7,[6,4]],3];
b=[];
flaten(b,a);
console.log(b);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-16 06:19:25