Home > front end >  JS comparing and modifying nested array items inside array
JS comparing and modifying nested array items inside array

Time:10-03

What is the correct / best practice way to perform the following?

I have an array that contains a dynamic number of arrays within it. Each nested array is built like so: (the values change obviously)

["100",{"value":"0.10","amount":"6000"}]

In some of the nested arrays, the first item ("100" in the example) repeats itself. In such case, I would like to add the second item (the key-value pairs) to the nested array.

Example:

Original Array-

[
["631",{"value":"0.10","amount":"6000"}],
["100",{"value":"0.20","amount":"5000"}],
["631",{"value":"0.30","amount":"7000"}]
]

Desired Output-

[
["631",{"value":"0.10","amount":"6000"}, {"value":"0.30","amount":"7000"}],
["100",{"value":"0.20","amount":"5000"}]
]

I've thought about iterating through the original array and then performing an if comparison but couldn't reach the exact desired output format. Any help? Thanks in advance.

CodePudding user response:

I did use one for and one conditional if

data = [
         ["631",{"value":"0.10","amount":"6000"}],
         ["100",{"value":"0.20","amount":"5000"}],
         ["631",{"value":"0.30","amount":"7000"}]
       ]
result = [];
for (key in data) {
  var index =result.findIndex((item) => item[0] === data[key][0])
  if(index<0){
    result.push(data[key])
  } else {
    result[index].push(data[key][1])
  }
 }
 console.log(result)

  • Related