Reputation: 598
I am trying to filter an array with the same elements by using the indexOf
function. But it fails and I do not understand why. To be more clear I want to filter by giving the position of an element, but it fails in array with two same elements. Could you please help ?
words = ['One', 'Two', 'myWord', 'Three', 'myWord', 'Four'];
words = words.filter(item => words.indexOf(item) != 2);
console.log(words);
// expected output: Array ['One', 'Two', 'Three', 'myWord', 'Four'],
// the first myWord in position 2 is excluded but not the one in position 4
Upvotes: 0
Views: 1091
Reputation: 1317
if What You need is really filter for a specific position then
const index = 2
words = words.filter((item, i) => i != index);
but it does not perform so well since has to loop over all the elements, I would opt for something like the following:
words = [...words.slice(0, index), ...words.slice(index+1)]
they behave the same as long as index >= 0
so a wrapping function would be a good thing.
There is any particular reason why You want to use indexOf
?
Upvotes: 0
Reputation: 7106
You don't need to use filter
for this. To remove an element at a specific index, just use array.splice(index, 1)
.
const words = ['One', 'Two', 'myWord', 'Three', 'myWord', 'Four']
words.splice(2, 1)
console.log(words)
const words2 = ['One', 'Two', 'myWord', 'Three', 'myWord', 'Four']
words2.splice(4, 1)
console.log(words2)
Upvotes: 1
Reputation: 395
Since the items in your array are identical, indexOf
always returns 0
for each item filtered. 0 != 1
always evaluates to true
. Since you always return true
from filter, you effectively are doing words.filter(item => true)
and filtering nothing.
May I ask what your intention is here? are you trying to uniqueify the array?
Upvotes: 0
Reputation: 89497
You can check if the index of an element is equal to the index of its first occurrence and keep only those elements.
words = ['myWord', 'myWord'];
words = words.filter((item,idx) => words.indexOf(item) === idx);
console.log(words);
You could also use a Set
, which is a more efficient data structure that doesn't allow duplicates.
words = ['myWord', 'myWord'];
words = [...new Set(words)];
console.log(words);
Upvotes: 1