'Compare Array of Objects in Javascript [closed]

I'd like to make this array:

[
   {main: "material", value: "blend"}, 
   {main: "material", value: "synthetic"}, 
   {main: "style", value: "curl"}, 
   {main: "style", value: "bob"}, 
   {main: "material", value: "premium"}
]

to this:

{
 material: ["blend", "synthetic", "premium"], 
 style: ["curl", "bob"]
}

I used two "for-loops" but it didn't work out well:( Quite newbie in Javascript🥲



Solution 1:[1]

You can use reduce to have that result

const data = [{
  main: "material",
  value: "blend"
}, {
  main: "material",
  value: "synthetic"
}, {
  main: "style",
  value: "curl"
}, {
  main: "style",
  value: "bob"
}, {
  main: "material",
  value: "premium"
}]

const finalResut = data.reduce((result, currentData) => {
  const {
    main,
    value
  } = currentData
  if (!result[main]) {
    result[main] = []
  }
  result[main].push(value)
  return result
}, {})

console.log(finalResut)
.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}

Solution 2:[2]

Using For Loop Here's how to do it. You Can Also Use reduce function as @Nick Vu Suggested.

var array = [
   {main: "material", value: "blend"}, 
   {main: "material", value: "synthetic"}, 
   {main: "style", value: "curl"}, 
   {main: "style", value: "bob"}, 
   {main: "material", value: "premium"}
]
var newArray = {material:[],style:[]}
for (var i =0;i<array.length;i++){
    if (array[i].main == "material")
    {newArray.material.push(array[i].value)}
    else
    {newArray.style.push(array[i].value)}}
console.log(newArray)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nick Vu
Solution 2 mrtechtroid