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

1

3 Answers 3

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)

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

0

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));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.