Home >Web Front-end >JS Tutorial >How to Combine Arrays Based on Unique Items in JavaScript?
Combining Arrays by Unique Items in JavaScript
In JavaScript, you can combine arrays based on unique items using a combination of object properties and loop functions.
Solution:
Start by creating an empty array newCells to store the combined results. Then iterate through each element in the original array:
<code class="js">for (var i = 0; i <p>This code will iterate through the totalCells array and check if an object with the current line number already exists in newCells. If not, it creates a new object with the line number and initializes an empty cellWidth array. Then it pushes the current cell width into the cellWidth array.</p> <p>The resulting newCells array will contain objects with unique lineNumber properties and arrays of cellWidth values combined based on the line numbers.</p> <p><strong>Example Output:</strong></p> <p>Applying the above solution to the provided sample input:</p> <pre class="brush:php;toolbar:false"><code class="js">totalCells = [ { cellwidth: 15.552999999999999, lineNumber: 1 }, { cellwidth: 14, lineNumber: 2 }, { cellwidth: 14.552999999999999, lineNumber: 2 }, { cellwidth: 14, lineNumber: 1 } ]; // Code to combine arrays based on unique line numbers // ... // Output console.log(newCells);</code>
Will output:
<code class="js">[ { lineNumber: 1, cellWidth: [15.552999999999999, 14], }, { lineNumber: 2, cellWidth: [14, 14.552999999999999], }, ]</code>
The above is the detailed content of How to Combine Arrays Based on Unique Items in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!