Array Element's Index is False

Viewed 42

In my code, I'm trying to map through an array and find an element. Then, I will replace that element with a string. The problem is, the index is -1. And, wrong element is replaced with the string. What is the cause of this problem and how can I fix this? My stackblitz and code is down below.

JS:

const arr = ['this', 'is', '<a/>', 'apple'];
const index = arr.indexOf(arr.includes('<'));
console.log(index);

const newArray = arr.map((arrayElement) => {
  arr.splice(index, 1, 'blocked');
  return arrayElement;
});

console.log(newArray);

https://stackblitz.com/edit/js-z6cpdd?file=index.js%3AL9

1 Answers

You have a number of issues. If you want to supply multiple strings to includes, you need to call includes multiple times, and you need to call it on the string values, not the array. In your scenario it's easier to use a regex match with a character class in findIndex. Secondly, you can simply call splice on the array (noting that it changes the original array), instead of using map:

const arr = ['this', 'is', '<a/>', 'apple'];
const index = arr.findIndex(s => s.match(/[<>/]/));

arr.splice(index, 1, 'blocked');

console.log(arr);

Related