Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion with how indexOf works in JS

Tags:

javascript

I am new to JS and was trying to learn how to properly work with indexOf in JS, that is, if you look at the code below:

var sandwiches = ['turkey', 'ham', 'turkey', 'tuna', 'pb&j', 'ham', 'turkey', 'tuna'];

var deduped = sandwiches.filter(function (sandwich, index) {
    return sandwiches.indexOf(sandwich) === index;
});

// Logs ["turkey", "ham", "tuna", "pb&j"]
console.log(deduped);

I am trying to remove duplicates but wanted to ask two questions. Firstly, in here return sandwiches.indexOf(sandwich) === index; why we need to use "== index;". Secondly, since indexOf returns index like 0, 1 or 2 ... then why when we console.log(deduped) we get array of names instead of array of indexes. Hope you got my points

like image 281
Dickens Avatar asked Sep 14 '19 11:09

Dickens


2 Answers

You use a method of Javascript Array that is filter, this method take a function that returns a boolean.

The function filter returns a new Array based on the function passed applied to each entry.

If the function return true, then the entry is included in the new Array, otherwise is discarded.

As the functions check the indexOf an entry to be the current index is true for the first occurrency of the entry.

All the duplications will fail the expression as they are not the first index found by indexOf, so they are discarded.

like image 142
Mario Santini Avatar answered Sep 29 '22 02:09

Mario Santini


  1. since the logic is to remove the duplicates from the array, in your example, you have "turkey" as duplicates. the "turkey" exists in position 0,2,6 so whenever you call indexOf("turkey") always returns 0 because the indexOf function returns the first occurrence of a substring. so for the elements in position 2 & 6 the condition fails. then it won't return that element.

  2. That is how the filter works in javascript. it evaluates the condition and returns true or false that indicates whether an element to be included in the new array or not, in your example the condition is return sandwiches.indexOf(sandwich) === index;

like image 37
Madhusudhan Aradya Avatar answered Sep 29 '22 01:09

Madhusudhan Aradya