Home >Web Front-end >JS Tutorial >How can you combine arrays in JavaScript while storing unique elements?

How can you combine arrays in JavaScript while storing unique elements?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-30 20:27:30701browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn