Search code examples
javascriptarraysunique

Take a specif field from an Array of Object and remove the duplicated ones


suppose with we have an array of objects like this: array = [{side:1, value:2}, {side:1, value:3}, {side:2, value:4}, {side:2, value: 4}, {side:3, value:3}] I want to create an array which contains only the side attibute without duplications like this: sideArray = [1,2,3]. These are the values of the side. How to do this?


Solution

  • You can use map() method to return array with side values and then Set and spread syntax to remove duplicates.

    var array = [{side:1, value:2}, {side:1, value:3}, {side:2, value:4}, {side:2, value: 4}, {side:3, value:3}]
    
    var result = [...new Set(array.map(e => e.side))];
    console.log(result)