Home > Article > Web Front-end > How to Merge an Array of Objects Based on Unique Items in JavaScript?
Merging an Array Based on Unique Items in JavaScript
In your inquiry, you aim to merge elements from an array based on a shared unique item. You provided an example where an array of objects with cellwidth and lineNumber properties needs to be combined based on the lineNumber.
To achieve this, you can employ the following steps:
By implementing these steps, you will create a new array (newCells) where each object represents a unique lineNumber and its cellWidth array contains all the unique cell widths associated with that line number.
<code class="javascript">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); }</code>
In summary, by leveraging the provided code snippet, you can effectively merge arrays based on unique item properties, resulting in a new array with distinct line numbers and associated cell widths.
The above is the detailed content of How to Merge an Array of Objects Based on Unique Items in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!