This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Test for value in Javascript Array
Best way to find an item in a JavaScript Array ?
Javascript - array.contains(obj)
I usually program in python but have recently started to learn JavaScript.
In python this is a perfectly valid if statement:
list = [1,2,3,4]
x = 3
if x in list:
print "It's in the list!"
else:
print "It's not in the list!"
but I have had poblems doing the same thing in Javascript.
How do you check if x is in list y in JavaScript?
Use indexOf which was introduced in JS 1.6. You will need to use the code listed under "Compatibility" on that page to add support for browsers which don't implement that version of JS.
JavaScript does have an in operator, but it tests for keys and not values.
p.s. original answer is from 2011, now it's supported by all browsers in use. https://caniuse.com/?search=indexof
In javascript you can use
if(list.indexOf(x) >= 0)
p.s. only ancient browsers don't support it
https://caniuse.com/?search=indexof
in more genric way you can do like this-
//create a custopm function which will check value is in list or not
Array.prototype.inArray = function (value)
// Returns true if the passed value is found in the
// array. Returns false if it is not.
{
var i;
for (i=0; i < this.length; i++) {
// Matches identical (===), not just similar (==).
if (this[i] === value) {
return true;
}
}
return false;
};
then call this function in this way-
if (myList.inArray('search term')) {
document.write("It's in the list!")
}
Related
This question already has answers here:
Why can't I use Array#includes for a nested array?
(5 answers)
How to compare arrays in JavaScript?
(61 answers)
Closed 3 months ago.
TL;DR: the JavaScript code below returns false where I'm expecting a true, what's the best workaround?
console.log([['a']].includes(['a']))
I'm pushing arrays into arrays (to work with google sheets ranges in apps script, but the behaviour is the same in regular JavaScript).
I'd like to check if my parent array (let's call it [['a']]) contains specific child array (such as ['a']).
Unfortunately array.includes() doesn't seem to work as expected when the parameter is an array. (the code above returns false when it should be true as far as I know)
Am I missing anything? What do you think would be the best workaround?
The problem is array comparison.
console.log(['a'] == ['a']); //false
As the .includes() method loops through the array on which it is being called, it checks each element to see if it is equal to the value being tested for, until it finds a match, or checks every element of the array. As you can see above, when the value being tested is an array, it will not work.
A work around would be to write your own .includes() function in which you loop through all the child arrays in the parent array, and for each child array, loop through every element, testing whether it is equal to the corresponding element in the test array. You can use the .every() method for this.
let array = [['a']];
function includesArray(parentArray, testArray) {
for (let i = 0; i < parentArray.length; i++) {
if (parentArray[i].every(function(value, index) { return value === testArray[index]})) {
return true;
}
}
return false;
}
console.log(includesArray(array, ['a'])); //true
console.log(includesArray(array, ['b'])); //false
One quick alternative is to compare the JSON strigified arrays instead of comparing arrays directly.
console.log([['a']].map(x => JSON.stringify(x)).includes(JSON.stringify(['a'])))
This question already has answers here:
Short circuit Array.forEach like calling break
(30 answers)
Closed 3 years ago.
I'm working on a homework problem using JavaScript. I have a solution that currently works, but I am sure that it is not the most efficient way to do it. I am iterating over an array to check if any element meets a certain condition. But there doesn't seem to be a way to exit the forEach() function early. In other languages, I have used break to quit a forEach loop early. Does something similar exist in JavaScript?
My code (simplified for this question):
let conditionMet = false;
numbers.forEach((number) => {
if (number % 3 === 0) {
conditionMet = true;
// break; <-- does not work!
}
});
Rather than using Array.forEach, you can use Array.some (see docs). This function iterates over the elements of the array, checking to see if any element meets a certain condition. If an element is found that meets the condition, the function stops iteration, and returns true. If not, the function returns false. This means that you can also skip the step of initializing conditionMet to false.
Your code can therefore be simplified as:
let conditionMet = numbers.some(number => (number % 3 === 0));
You can’t break .foreach() loop unless through an exception
So you can choose another tool like a simple for loop.
This question already has answers here:
Check variable equality against a list of values
(16 answers)
Closed 5 years ago.
This one is probably fairly straightforward, but I haven't succeeded in finding an answer as of yet. Anyway, what I want to do is compare one value against a group of others, and run the script if it matches one of them. Here's the verbose version of I want to do, which works fine, but I'm assuming there's a smarter, less verbose way to achieve this?
function updatePosition(e) {
if((e.target.innerHTML == 1) || (e.target.innerHTML == 4) ||
(e.target.innerHTML == 7)) {
console.log(e.target.innerHTML)
}
}
You can store all the valid comparison inside an array. Then you can use Array#Find() to get a matching value. If there is no matching value, you will get undefined
function updatePosition(num) {
let validNumbers = [1,4,7];
console.log(validNumbers.find(valid => valid === num));
}
updatePosition(4);
updatePosition(9);
This question already has answers here:
IE8 for...in enumerator
(3 answers)
How do I check if an object has a specific property in JavaScript?
(31 answers)
Closed 8 years ago.
var arr=["test"]; for(var e in arr) console.log(e);
in IE11's console it outputs:
0 contains remove clear add addAll(all properties)
and in chrome's console only outputs 0, which is expected.
how to fix it in IE? I know I can use for(var i=0;i<arr.length;i++) to solve it.
but I just wonder why IE outputs all the properties.
using IE11 and looks ok to me
if you want more control use Array.prototype.forEach method.It accepts a callback which have three parameters.They are element,their index and the array itself.Try
var arr=["test",'ball'];arr.forEach(function(element,index){
console.log(index);
});
Use the hasOwnProperty method.
Example:
var arr = ["test"];
for (var e in arr) {
if (arr.hasOwnProperty(e)) {
console.log(e);
}
}
Good explanation on why this is necessary: https://stackoverflow.com/a/12017703/1387396
Details on the hasOwnProperty method and its use in for .. in loops: Object.prototype.hasOwnProperty() - JavaScript | MDN
This question already has answers here:
How to compare arrays in JavaScript?
(55 answers)
Closed 9 years ago.
Long story short. Why is
console.log(obj.hello[0].w == ['hi','hi']); // false
in the following:
var obj = {
'hello':[
{'w':['hi','hi']}
]
}
console.log(obj.hello[0].w); // ['hi','hi']
console.log(obj.hello[0].w == ['hi','hi']); // false ??? Why is it false?
console.log(obj.hello[0].w[0] == 'hi'); // true
console.log(obj.hello[0].w[0] == ['hi']); // true
console.log(obj.hello[0].w[0] === ['hi']); // false
console.log(obj.hello[0].w[0] === 'hi'); // true
If obj.hello[0].w != ['hi','hi'], then what is the 'real' value of obj.hello[0].w?
EDIT: I first thought the problem was about JSON but it turned out it's about comparing objects. Sorry, for duplicate.
In addition to #MightyPork's answer, there are workarounds that are very simple.
The easiest way (supported by modern browsers) is to use JSON.stringify().
JSON.stringify(['hi', 'hi')) === JSON.stringify(['hi', 'hi')) // true
If your browser doesn't support JSON nativley you can include the JSON-js library on your page, which has the same syntax.
This isn't a complete solution. For example, functions always return null, except when they are class instances.
function a(){ this.val = "something"; }
JSON.stringify([a]) // "[null]"
JSON.stringify([new a]) // "[{"val":"something"}]"
You cannot compare arrays like if they were simple variables. You're comparing references to two different arrays, and that will always be false, regardless of their contents.
If you want to do the check, you will have to compare each value individually.