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

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



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 ]
]
Updated on: 2020-09-14T08:47:28+05:30

254 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements