How to get distinct value from array in javascript?

by elisha_langworth , in category: Javascript , a year ago

How to get distinct value from array in javascript?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by filiberto , a year 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.

Related Threads:

How to get # url value with javascript?
How to get 2 distinct rows from 1 row with 3 tables in sql oracle?
How to get second value from array in laravel?
How to get single value from array in vue.js?
How to aggregate distinct array field in mongodb?
How to get distinct rows in laravel?