Home > Article > Web Front-end > How can you combine arrays in JavaScript while storing unique elements?
Combining Arrays with Unique Elements in JavaScript
To consolidate arrays based on unique items, you can leverage the following technique:
<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>
This code iterates through the input array, examining each object's lineNumber property. For each unique lineNumber, a new object is created within the newCells array. This object stores the lineNumber and an empty array named cellWidth.
As the code progresses, it checks for existing objects with the same lineNumber and, if found, appends the current object's cellWidth to that object's cellWidth array. By the end of the iteration, you'll have an array where each object has a lineNumber property and a cellWidth array containing all the cellWidth values for that unique lineNumber.
The above is the detailed content of How can you combine arrays in JavaScript while storing unique elements?. For more information, please follow other related articles on the PHP Chinese website!