Home > Back-end >  How to get these 2D array elements summed if there are duplicates?
How to get these 2D array elements summed if there are duplicates?

Time:06-02

I have seen a couple of Output

CodePudding user response:

Try:

const array = [
  [2, 'name1','something',15],
  [3, 'name10','something',5],
  [5, 'name20','something',20],
  [2, 'name15','something',3]
]

const newArray = [...new Set(array.map(row => row[0]))].map(item => {

  const relevantRows = array.filter(row => row[0] === item)

  if (relevantRows.length > 1) {

    return [
      ...relevantRows[0].slice(0, 3), 
      relevantRows.flatMap(row => row[3])
                  .reduce((prev, curr) => prev   curr, 0)
    ]

  } else {
    return relevantRows[0] 
  }

})

Commented:

const array = [
  [2, 'name1', 'something', 15],
  [3, 'name10', 'something', 5],
  [5, 'name20', 'something', 20],
  [2, 'name15', 'something', 3]
]

// For each unique value in the first index..
const newArray = [...new Set(array.map(row => row[0]))].map(item => {
  // Get all rows that contain value at first index.
  const relevantRows = array.filter(row => row[0] === item)
  // If more than one result..
  if (relevantRows.length > 1) {
    // 'Change' array item to earliest appearing row with sum of last indexes.
    return [
      ...relevantRows[0].slice(0, 3), 
      relevantRows.flatMap(row => row[3])
                  .reduce((prev, curr) => prev   curr, 0)
    ]
  // If only one result, change array item to the row.
  } else { 
    return relevantRows[0] 
  }
  
})
  • Related