Tengo esta matriz de objetos y quiero organizar los objetos en función de sus unidades de esta manera:
const array = [ { unit: 5, id: 'five'}, { unit: 200, id: 'some22'}, { unit: 100, id: 'recall'}, { unit: 5, id: 'some'}, ]; // Result : [ [ { unit: 5, id: 'five'}, { unit: 5, id: 'some'}, ], [ { unit: 6, id: 'some22'} ], [ { unit: 55, id: 'recall'} ], ]Nota: simplemente podemos usar el método de filtro para obtener la matriz, pero en mi caso no conocemos las unidades y solo queremos ordenarlas y organizarlas.
Un enfoque diferente que usa el método de compilación en matriz reduce , solo para crear una sola línea . Detalles de la subestimada función de reduce Array.prototype.reduce
// Initial Data const array = [ { unit: 5, id: 'five'}, { unit: 200, id: 'some22'}, { unit: 100, id: 'recall'}, { unit: 5, id: 'some'}, ]; let result = array.reduce (function(last, next){ // find index of a List with matching unit let index = last.findIndex((itemList) => itemList.some( item => item.unit == next.unit)); if(index == -1){ // if no match was found index = last.push([]) - 1; // add an empty Array and set the index } last[index].push(next); // add the Entry to the selected List return last; }, []) console.info(result);Por cierto: supongo que los datos de resultados publicados son incorrectos, ya que las "unidades" para some22 y recordar no coinciden con los datos iniciales. Si esta suposición es incorrecta, aclare
Extra: solo por diversión y risas, todo como una sola línea:
( No intentes esto en casa ;-) )
const array = [ { unit: 5, id: 'five'}, { unit: 200, id: 'some22'}, { unit: 100, id: 'recall'}, { unit: 5, id: 'some'}, ]; console.info( array.reduce((p, c) => ((p.find( l => l.some(i => i.unit == c.unit)) || p[p.push([]) - 1]).push(c), p), []));Podrías usar un mapa :
const array = [ { unit: 5, id: 'five'}, { unit: 200, id: 'some22'}, { unit: 100, id: 'recall'}, { unit: 5, id: 'some'}, ]; const unitGroups = new Map(); for (const obj of array) { if (!unitGroups.has(obj.unit)) { unitGroups.set(obj.unit, []); } unitGroups.get(obj.unit).push(obj); } const result = Array.from(unitGroups.values()); console.log(result);