Home > Web Front-end > JS Tutorial > body text

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

Patricia Arquette
Release: 2024-10-30 20:27:30
Original
630 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!