How to get distinct value from array in javascript?

by elisha_langworth , in category: Javascript , 6 months ago

How to get distinct value from array in javascript?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by filiberto , 6 months ago

@elisha_langworth 

There are multiple ways to get distinct values from an array in JavaScript. Here are a few examples:

  1. Using the Set object:
1
2
3
const array = [1, 2, 2, 3, 3, 4, 5, 5];
const distinctArray = [...new Set(array)];
console.log(distinctArray); // Output: [1, 2, 3, 4, 5]


  1. Using a filter and indexOf method:
1
2
3
4
5
const array = [1, 2, 2, 3, 3, 4, 5, 5];
const distinctArray = array.filter((value, index, self) => {
  return self.indexOf(value) === index;
});
console.log(distinctArray); // Output: [1, 2, 3, 4, 5]


  1. Using the reduce method:
1
2
3
4
5
6
7
8
const array = [1, 2, 2, 3, 3, 4, 5, 5];
const distinctArray = array.reduce((unique, value) => {
  if (!unique.includes(value)) {
    unique.push(value);
  }
  return unique;
}, []);
console.log(distinctArray); // Output: [1, 2, 3, 4, 5]


All these methods will give you an array with distinct values from the original array.