Tengo una matriz con múltiples objetos. Me gustaría dividir esta matriz en múltiples matrices. El criterio para dividir es el elemento continent.

MyArray = [{continent:"europe", fruit:"orange", value:2},
           {continent:"asia", fruit:"banana", value:2},
           {continent:"europe", fruit:"apple", value:2},
           {continent:"asia", fruit:"apple", value:5}
          ];

Salida:

[
 [{continent:"europe", fruit:"orange", value:2},
  {continent:"europe", fruit:"apple" value:2}
 ], [
  {continent:"asia", fruit:"banana", value:2},
  {continent:"asia", fruit:"apple" value:5}]
];
3
pifou 25 feb. 2018 a las 17:55

3 respuestas

La mejor respuesta

Puede buscar la matriz con el mismo continente y actualizar esta matriz o insertar una nueva matriz con el objeto real.

var array = [{ continent: "europe", fruit: "orange", value: 2 }, { continent: "asia", fruit: "banana", value: 2 }, { continent: "europe", fruit: "apple", value: 2 }, { continent: "asia", fruit: "apple", value: 5 }],
    grouped = array.reduce(function (r, o) {
        var group = r.find(([{ continent }]) => continent === o.continent)
        if (group) {
            group.push(o);
        } else {
            r.push([o]);
        }
        return r;
    }, []);
    
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
2
Nina Scholz 25 feb. 2018 a las 15:32

Obtenga el continente y use filter para obtener los elementos coincidentes

var MyArray = [{
  continent: "europe",
  fruit: "orange",
  value: 2
}, {
  continent: "asia",
  fruit: "banana",
  value: 2
}, {
  continent: "europe",
  fruit: "apple",
  value: 2
}, {
  continent: "asia",
  fruit: "apple",
  value: 5
}];
var getAllContinents = [];
 // getting the unique continent name
MyArray.forEach(function(item) {
  // if the continent  name is not present then push it in the array
  if (getAllContinents.indexOf(item.continent) === -1) {
    getAllContinents.push(item.continent)
  }
})
var modifiedArray = [];
//iterate over the continent array and find the matched elements where 
// continent name is same
getAllContinents.forEach(function(item) {
  modifiedArray.push(MyArray.filter(function(cont) {
    return cont.continent === item
  }))
})
console.log(modifiedArray)
0
brk 25 feb. 2018 a las 15:05

También puede crear un objeto con claves que tengan valores de propiedad especificada. Esto le permitirá acceder a la matriz deseada muy fácilmente.

Usted puede usar:

Ejemplo:

let data = [{continent:"europe", fruit:"orange", value:2},      
            {continent:"asia", fruit:"banana", value:2},
            {continent:"europe", fruit:"apple", value:2},
            {continent:"asia", fruit:"apple", value:5}];

let result = data.reduce((acc, obj) => {
  acc[obj.continent] = acc[obj.continent] || [];
  acc[obj.continent].push(obj);
  return acc;
}, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
0
Mohammad Usman 25 feb. 2018 a las 15:28