0

I have an array of objects and am looking for the most efficient way with es6 to group them based on the material_id

var data=[
  {material_id:1, item:'test'},
  {material_id:1,  item:'test2'},
  {material_id:2,  item:'test2'},
]

So at the end i want to get

var final_data = [
  1,2
 ]

THat is the id's from the grouped material_id

SO i have tried this but am stuck on how to proceed further

let final_data = [];
data.forEach(item=>{
      //stuck here
})

I have checked on This question but it doesnt seem to show a grouping

Geoff
  • 6,277
  • 23
  • 87
  • 197

3 Answers3

2

You can map() to get an array of all ids and then use Set to remove duplicates

var data=[
  {material_id:1, item:'test'},
  {material_id:1,  item:'test2'},
  {material_id:2,  item:'test2'},
]
let res = [...new Set(data.map(x => x.material_id))]
console.log(res)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
1

You can use reduce to group your array and use Object.keys to get key of result.

var data=[
  {material_id:1, item:'test'},
  {material_id:1,  item:'test2'},
  {material_id:2,  item:'test2'},
]

let result = data.reduce((r, a) => {

  const {
    material_id,
    item
  } = a;

  r[a.material_id] = [...r[a.material_id] || [], {
    material_id,
    item
  }];

  return r;
}, {});


console.log(Object.keys(result));
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
1

With a unique function, I was able to solve the problem like so:

const unique = (value, index, self) => {
    return self.indexOf(value) === index
}


const data =[
  {material_id:1, item:'test'},
  {material_id:1,  item:'test2'},
  {material_id:2,  item:'test2'},
];

var final_data = [];

for(var i in data) {
    let row = data[i];
    final_data.push(row.material_id);
}
final_data = final_data.filter(unique);

console.log(final_data);