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

When working with arrays of sub-arrays, you may need to remove duplicates based on the first element (0th index) of each sub-array. This is common when dealing with data like subject-marks pairs where you want only unique subjects.

Let's say the following is our array:

var subjectNameAlongWithMarks = [
    ["JavaScript", 78],
    ["Java", 56],
    ["JavaScript", 58],
    ["MySQL", 77],
    ["MongoDB", 75],
    ["Java", 98]
];
console.log("Original array:", subjectNameAlongWithMarks);
Original array: [
  [ 'JavaScript', 78 ],
  [ 'Java', 56 ],
  [ 'JavaScript', 58 ],
  [ 'MySQL', 77 ],
  [ 'MongoDB', 75 ],
  [ 'Java', 98 ]
]

Above, we have repeated values like "JavaScript" and "Java" that appear multiple times. We need to remove duplicates by comparing the 0th index values.

Using Set() with filter()

The most elegant solution uses JavaScript's Set() along with filter() to track seen values:

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("Filtered array:", distinctResult);
Filtered array: [
  [ 'JavaScript', 78 ],
  [ 'Java', 56 ],
  [ 'MySQL', 77 ],
  [ 'MongoDB', 75 ]
]

How It Works

The solution uses destructuring to extract the first element as value. The Set() tracks seen values:

  • this.has(value) - checks if the value exists in the Set
  • this.add(value) - adds the value to the Set and returns the Set
  • !!this.add(value) - converts the Set to boolean (always true)
  • !this.has(value) && !!this.add(value) - returns true only for first occurrence

Alternative Approach Using indexOf()

You can also use indexOf() to find the first occurrence:

var subjectNameAlongWithMarks = [
    ["JavaScript", 78],
    ["Java", 56],
    ["JavaScript", 58],
    ["MySQL", 77]
];

var distinctResult = subjectNameAlongWithMarks.filter((item, index, array) => {
    return array.findIndex(arr => arr[0] === item[0]) === index;
});

console.log("Using indexOf approach:", distinctResult);
Using indexOf approach: [
  [ 'JavaScript', 78 ],
  [ 'Java', 56 ],
  [ 'MySQL', 77 ]
]

Conclusion

The Set() approach is more efficient for large datasets as it has O(n) complexity compared to indexOf()'s O(n²). Use Set() with filter() to remove duplicates based on the first element of sub-arrays.

Updated on: 2026-03-15T23:18:59+05:30

304 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements