EN
JavaScript find string in array
1
answers
11
points
I have array of elements:
var elements = [
"x",
"y",
"my_element",
"z"
];
How can I detect if this array contains string "my_element" ?
What is the most recommended way doing that?
1 answer
1
points
The easiest way of doing that is just use indexOf method on our array of elements.
Practical example to detect if the element exists in our array:
// ONLINE-RUNNER:browser;
var elements = [
"x", // index: 0
"y", // index: 1
"my_element", // index: 2
"z", // index: 3
];
var index = elements.indexOf("my_element");
if (index == -1) {
console.log("Element doesn't exist");
} else {
console.log("Element exists under index: " + index);
}
Additionaly we get index of this element in this array.
Flow:
var index = elements.indexOf("my_element");
- If the result index is -1 then the array doesn't contains the element we are looking for.
- If the index is any other then the element is under this index.
Practical function
We can also create practical function and enclose the logic:
// ONLINE-RUNNER:browser;
function arrayContains(array, element) {
return (array.indexOf(element) > -1);
}
var elements = [
"x", // index: 0
"y", // index: 1
"my_element", // index: 2
"z", // index: 3
];
console.log( arrayContains(elements, "my_element") ); // true
console.log( arrayContains(elements, "my_element_2") ); // false
Index of from specific index
We can also use indexOf to find element from some specific index in our array.
// ONLINE-RUNNER:browser;
var elements = [
"x", // index: 0
"y", // index: 1
"my_element", // index: 2
"z", // index: 3
"a", // index: 4
"my_element", // index: 5
"b", // index: 6
"c" // index: 7
];
// we start to find the string from the index 3 in our array
var index = elements.indexOf("my_element", 3);
if (index == -1) {
console.log("Element doesn't exist");
} else {
console.log("Element exists under index: " + index);
}
0 comments
Add comment