Home  >  Article  >  Web Front-end  >  How to Merge Arrays of Objects Based on a Unique Property in JavaScript?

How to Merge Arrays of Objects Based on a Unique Property in JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-10-31 18:15:02862browse

How to Merge Arrays of Objects Based on a Unique Property in JavaScript?

Combining Arrays Based on Unique Items in JavaScript

Merging arrays can be a common task in JavaScript, especially when needing to combine data based on specific criteria. In this particular instance, the goal is to combine an array of objects based on a shared lineNumber property, resulting in an array of objects with a lineNumber and an array of corresponding cellWidth values.

To achieve this, the following code snippet can be used:

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);
}

Breaking down the code:

  • A new array is initialized as newCells to store the merged results.
  • The code iterates through the totalCells array using a for loop.
  • For each object in totalCells, the lineNumber is extracted.
  • An if statement is used to check if an object with the current lineNumber already exists in newCells. If it does not exist, a new object with the lineNumber and an empty cellWidth array is added to newCells.
  • The cellWidth value of the current totalCells object is pushed to the cellWidth array of the matching object in newCells.

By following these steps, the code combines the totalCells array into newCells, where each object has a unique lineNumber and an array of cellWidth values corresponding to that lineNumber.

The above is the detailed content of How to Merge Arrays of Objects Based on a Unique Property 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