Remove values in an array by comparing the items 0th index in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

Let’s say the following is our array &mius;

var subjectNameAlongWithMarks = [
   ["JavaScript", 78],
   ["Java", 56],
   ["JavaScript", 58],
   ["MySQL", 77],
   ["MongoDB", 75],
   ["Java", 98]
]

Above, we have repeated values, which we need to remove by comparing the duplicate values 0<sup>th</sup> index. Use the concept of Set() from JavaScript for this −

Example

var subjectNameAlongWithMarks = [
   ["JavaScript", 78],
   ["Java", 56],
   ["JavaScript", 58],
   ["MySQL", 77],
   ["MongoDB", 75],
   ["Java", 98]
]
var distinctResult = subjectNameAlongWithMarks.filter(function ([value]){
   return !this.has(value) && !!this.add(value)
}, new Set())
console.log(distinctResult);

To run the above program, you need to use the following command −

node fileName.js.

Output

Here, my file name is demo196.js. This will produce the following output −

PS C:\Users\Amit\javascript-code> node demo196.js
[
   [ 'JavaScript', 78 ],
   [ 'Java', 56 ],
   [ 'MySQL', 77 ],
   [ 'MongoDB', 75 ]
]
raja
Published on 14-Sep-2020 08:47:07
Advertisements