Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the common values in an array

For example i am having an array of data as below

var arrData = ["40-25",null,null,"40-25","50-48",null,"30-25","40-23","50-48","30-25",null,"50-48","40-45","40-45","40-45","40-50","40-50",null,null,null,null,null,"50-48"]

i need to list the same data as below in javascript

var arrDataSorted = ["40-25","50-48","30-25","40-23","40-45","40-50","40-50"]

need only the common data that replicates also the null to be removed.

What is the best solution to solve this.

like image 749
Mohammed Hablullah Avatar asked Nov 06 '25 14:11

Mohammed Hablullah


1 Answers

You can try using Array.prototype.filter() to remove null values and Set to get the unique values. Finally use the Spread syntax (...) to transform the set result into an array.

Try the following way:

var arrData = ["40-25",null,null,"40-25","50-48",null,"30-25","40-23","50-48","30-25",null,"50-48","40-45","40-45","40-45","40-50","40-50",null,null,null,null,null,"50-48"];

var arrDataSorted = [...new Set(arrData.filter(i => i))];
console.log(arrDataSorted);
like image 145
Mamun Avatar answered Nov 08 '25 09:11

Mamun