You can use a for loop in JavaScript to find all the indexes of a specific element in an array. Here’s an example:
let arr = [1, 2, 3, 2, 4, 2];
let search = 2;
let indexes = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] === search) {
indexes.push(i);
}
}
if (indexes.length) {
console.log(`The element "${search}" can be found at indexes ${indexes.join(', ')}`);
} else {
console.log(`The element "${search}" could not be found in the array`);
}
This will output The element "2" can be found at indexes 1, 3, 5
.
+ There are no comments
Add yours