7

My data had nested objects with array. I want to make the nested object atrribute unique from the output. Currenly I'm using lodash v4 above, I found a solution suitable but only works in lodash v3.

Data

[{
   menu: { id: 1 },
   other: { data: "another1" }
},
{
   menu: { id: 2 },
   other: { data: "another2" }
},
{
   menu: { id: 1 },
   other: { data: "another1" }
}]

Expected output

[{
   menu: { id: 1 },
   other: { data: "another1" }
},
{
   menu: { id: 2 },
   other: { data: "another2" }
}]

Similar lodash v3 solution is here. What is the solution for v4? Solution without lodash still accepted as long as the codes are running faster and simple.

3 Answers 3

7

You can use uniq method as below.

var arr = [{
  menu: {
    id: 1
  }
}, {
  menu: {
    id: 2
  }
}, {
  menu: {
    id: 1
  }
}];

var unique = _.uniq(arr, 'menu.id');
console.log(unique);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min.js"></script>


With lodash 4.x.x, use uniqBy

var arr = [{
  menu: {
    id: 1
  },
  other: {
    data: "another1"
  }
}, {
  menu: {
    id: 2
  },
  other: {
    data: "another2"
  }
}, {
  menu: {
    id: 1
  },
  other: {
    data: "another1"
  }
}];

console.log(_.uniqBy(arr, 'menu.id'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

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

Comments

1

Without lodash .using Array#reduce

var a =[{
   menu: { id: 1 },
   other: { data: "another1" }
},
{
   menu: { id: 2 },
   other: { data: "another2" }
},
{
   menu: { id: 1 },
   other: { data: "another1" }
}]

var res =[];
 var fin =a.reduce((a,b)=> {
if(!res.includes(b.menu.id)){
res.push(b.menu.id)
a.push(b)
}
return a;
},[])
console.log(fin)

Comments

0

maybe

_.uniqBy(yourarray, e=>e.menu.id)

var data = [{
   menu: { id: 1 },
   other: { data: "another1" }
},
{
   menu: { id: 2 },
   other: { data: "another2" }
},
{
   menu: { id: 1 },
   other: { data: "another1" }
}]

console.log(_.uniqBy(data, e=>e.menu.id));
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.