Combining Arrays Based on Unique Items in JavaScript
Merging arrays can be a common task in JavaScript, especially when needing to combine data based on specific criteria. In this particular instance, the goal is to combine an array of objects based on a shared lineNumber property, resulting in an array of objects with a lineNumber and an array of corresponding cellWidth values.
To achieve this, the following code snippet can be used:
var newCells = []; for (var i = 0; i < totalCells.length; i++) { var lineNumber = totalCells[i].lineNumber; if (!newCells[lineNumber]) { // Add new object to result newCells[lineNumber] = { lineNumber: lineNumber, cellWidth: [] }; } // Add this cellWidth to object newcells[lineNumber].cellWidth.push(totalCells[i].cellWidth); }
Breaking down the code:
By following these steps, the code combines the totalCells array into newCells, where each object has a unique lineNumber and an array of cellWidth values corresponding to that lineNumber.
Isenção de responsabilidade: Todos os recursos fornecidos são parcialmente provenientes da Internet. Se houver qualquer violação de seus direitos autorais ou outros direitos e interesses, explique os motivos detalhados e forneça prova de direitos autorais ou direitos e interesses e envie-a para o e-mail: [email protected]. Nós cuidaremos disso para você o mais rápido possível.
Copyright© 2022 湘ICP备2022001581号-3