Search code examples
javascriptlodash

How to select particular items in an array and form a new array using ES6 JS /Lodash


For example this is the original array:

const animals = [{
    name: "Lion",
    image: "a url",
    gender: "male",
    age: "2"
  },
  {
    name: "Lion",
    image: "a url",
    gender: "male",
    age: "3"
  },
  {
    name: "Lion",
    image: "a url",
    gender: "male",
    age: "4"
  },
  {
    name: "Lion",
    image: "a url",
    gender: "male",
    age: "6"
  },
  {
    name: "Tiger",
    image: "a url",
    gender: "male",
    age: "6"
  },
]

I want to form a new array that holds only unique datas & consisiting of only name and image

So the new array should look like

const newArray = [{
    name: "Lion",
    image: "a url"
  },
  {
    name: "Tiger",
    image: "a url"
  }

]

how can I form this newArray using less amount of code particularly using ES6 JS or using lodash


Solution

  • Use _.uniqBy() to get the distinct values, and Array#map with _.pick() to get just the props you want:

    const animals = [{"name":"Lion","image":"a url","gender":"male","age":"2"},{"name":"Lion","image":"a url","gender":"male","age":"3"},{"name":"Lion","image":"a url","gender":"male","age":"4"},{"name":"Lion","image":"a url","gender":"male","age":"6"},{"name":"Tiger","image":"a url","gender":"male","age":"6"}];
    
    const result = _.uniqBy(animals, 'name').map((o) => _.pick(o, ['name', 'image']));
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>