Home >Web Front-end >JS Tutorial >How to Combine Arrays Based on Unique Items in JavaScript?

How to Combine Arrays Based on Unique Items in JavaScript?

DDD
DDDOriginal
2024-10-29 02:23:02323browse

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 < totalCells.length; i++) {
    var lineNumber = totalCells[i].lineNumber;
    // Check if an object for the current line number already exists in newCells
    if (!newCells[lineNumber]) {
        // Create a new object with the line number and an empty array to store cell widths
        newCells[lineNumber] = {
            lineNumber: lineNumber,
            cellWidth: []
        };
    }
    // Add the current cellWidth to the array in the new object
    newCells[lineNumber].cellWidth.push(totalCells[i].cellWidth);
}</code>

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.

The resulting newCells array will contain objects with unique lineNumber properties and arrays of cellWidth values combined based on the line numbers.

Example Output:

Applying the above solution to the provided sample input:

<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!

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