How do I check if an array includes a value in JavaScript?
Modern browsers have Array#includes, which does exactly that and is widely supported by everyone except IE:
console.log(['joe', 'jane', 'mary'].includes('jane')); //true
function checkInput(input, words) {
return words.some(word => input.toLowerCase().includes(word.toLowerCase()));
}
console.log(checkInput('"Definitely," he said in a matter-of-fact tone.',
["matter", "definitely"]));
let isInArray = arr.includes(valueToFind[, fromIndex])
// arr - array we're inspecting
// valueToFind - value we're looking for
// fromIndex - index from which the seach will start (defaults to 0 if left out)
// isInArray - boolean value which tells us if arr contains valueToFind
function droids(arr) {
let result = 'These are not the droids you're looking for';
for(let i=0; i<arr.length;i++) {
if (arr[i] === 'Droids') {
result = 'Found Droid';
}
}
return result;
}
// Uncomment these to check your work!
const starWars = ["Luke", "Finn", "Rey", "Kylo", "Droids"]
const thrones = ["Jon", "Danny", "Tyrion", "The Mountain", "Cersei"]
console.log(droids(starWars)) // should log: "Found Droids!"
console.log(droids(thrones)) // should log: "These are not the droi
//A simpler approach
console.log(starWars.includes('Droids') ? 'Droid Found' : 'These are not the droids you're looking for');
console.log(thrones.includes('Droids') ? 'Droid Found' : 'These are not the droids you're looking for');
function checkInput(input, words) {
return words.some(word => new RegExp(word, "i").test(input));
}
console.log(checkInput('"Definitely," he said in a matter-of-fact tone.',
["matter", "definitely"]));
function buildSearch(substrings) {
return new RegExp(
substrings
.map(function (s) {return s.replace(/[.*+?^${}()|[]]/g, '$&');})
.join('{1,}|') + '{1,}'
);
}
var pattern = buildSearch(['hello','world']);
console.log(pattern.test('hello there'));
console.log(pattern.test('what a wonderful world'));
console.log(pattern.test('my name is ...'));
function droids(arr) {
result = "These are not the droids you're looking for."
for (str of arr) {
if (str == 'Droids')
result = "Found Droids!"
}
return result;
}
javascript - Determine whether an array contains a value
var contains = function(needle) {
// Per spec, the way to identify NaN is that it is not equal to itself
var findNaN = needle !== needle;
var indexOf;
if(!findNaN && typeof Array.prototype.indexOf === 'function') {
indexOf = Array.prototype.indexOf;
} else {
indexOf = function(needle) {
var i = -1, index = -1;
for(i = 0; i < this.length; i++) {
var item = this[i];
if((findNaN && item !== item) || item === needle) {
index = i;
break;
}
}
return index;
};
}
return indexOf.call(this, needle) > -1;
};