-3

I'm using filteredArray to get unique values for my array. Is there a more concise way of doing this? I'm totally fine with the way it is, but just wanted more perspectives.

I tried new Set(.. but it gave me back the numbers as strings and that's not what I needed. However, I prolly implemented wrong or something.

function myFunction2() {
    const toReturn = Object.keys(list).map(key => list[key].idDealer);

    var filteredArray = toReturn.filter(function(item, pos){
        return toReturn.indexOf(item)== pos; 
      });

    return filteredArray;
}
Rod
  • 14,529
  • 31
  • 118
  • 230

3 Answers3

2

with the ES6 Syntax i think it will be much clearer

array = array.filter((item, index, array) => array.indexOf(item) == index)

item refers to the item in the array, index refers to the index of the item and array is the array reference

Gallaoui
  • 501
  • 4
  • 19
1

Concise would be to put that logic in another function.

function unique(value, index, self) { 
    return self.indexOf(value) === index;
}

return Object.keys(list).map(key => list[key].idDealer).filter(unique)
Steven Spungin
  • 27,002
  • 5
  • 88
  • 78
1

I use the following function. The advantage being that it works on an array of anything that can be stringified.

const unique = () => {
    const seen = {};
    return item => {
        const json = JSON.stringify( item );
        return seen.hasOwnProperty( json )
            ? false
            : ( seen[ json ] = true );
    };
};

const data = [
  { value: 'unique' },
  { value: 'not unique' },
  { value: 'not unique' }
];

const filtered = data.filter( unique() );

console.log( filtered );
Shilly
  • 8,511
  • 1
  • 18
  • 24