[Solved] How to merge multiple arrays in JavaScript with a first elements [closed]


You’re looking for the Set data structure. Create a set with all the arrays you have and you’ll have the duplicates removed.
To amend the other user’s answer:

// Have a single array to loop through.
var mainArray = [];
mainArray.push(["cat", "blue", "1"]);
mainArray.push(["cat", "red", "1"]);
mainArray.push(["cat", "yellow", "1"]);
mainArray.push(["dog", "blue", "1"]);
mainArray.push(["dog", "red", "1"]);

// Result Object.
var resultObject = {};
for (var i = 0; i < mainArray.length; i++) {
  if (!resultObject[mainArray[i][0]]) {
    resultObject[mainArray[i][0]] = [];
  }
  resultObject[mainArray[i][0]] = resultObject[mainArray[i][0]].concat(mainArray[i]);

}



 for (var key in resultObject) {
  if (resultObject.hasOwnProperty(key)) {
    resultObject[key] = new Set(resultObject[key])
    resultObject[key] = Array.from(resultObject[key])
  }
}
console.log(resultObject)

3

solved How to merge multiple arrays in JavaScript with a first elements [closed]