Check if value exists in array javascript [duplicate] - javascript

This question already has answers here:
Object comparison in JavaScript [duplicate]
(10 answers)
How to determine equality for two JavaScript objects?
(82 answers)
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 3 years ago.
I have this data
var selectedValue = [];
selectedValue.push({0:'Data A'});
selectedValue.push({1:'Data B'});
I want to check if my new data is already exists in that array. I'm trying to use includes()
function inArrayCheck(val) {
console.log(selectedValue.includes(val));
}
Then i try another way
function inArrayCheck(val) {
if (Object.values(selectedValue).indexOf(val) > -1) {
console.log(val);
}
}
both of them returning false when i input Data A

Objects will not be equal unless they have the same reference, even when they have the same key/value pairs. You can do the comparison after converting the objects to string using JSON.stringify with limited capability, like the order of elements in the object and the case of strings matters:
var selectedValue = [];
selectedValue.push({0:'Data A'});
selectedValue.push({1:'Data B'});
function inArrayCheck(val) {
return selectedValue.some(obj => JSON.stringify(obj) === JSON.stringify(val))
}
console.log(inArrayCheck({0:'Data A'}))

You are trying to find a value from an object which is inside an array. You can try like so:
var selectedValue = []; // this is an array
selectedValue.push({0:'Data A'}); // here you push an object to the array
selectedValue.push({1:'Data B'}); // to find the value later you need to find it inside the object!
// above three lines can also be written like so and are the same
// var selectedvalue1 = [{0:'Data A'}, {1:'Data B'}];
function inArrayCheck(val) {
selectedValue.forEach(function(element){
if (Object.values(element).indexOf(val) > -1) {
console.log('found value: ' + val);
}
});
}
inArrayCheck('Data A');
if you want to use includes you need to have an array like so:
var selectedValue = [];
selectedValue.push('Data A');
selectedValue.push('Data B');
// above three lines can also be written like so and are the same
// var selectedvalue1 = ['Data A', 'Data B'];
function inArrayCheck(val) {
console.log(selectedValue.includes(val));
}
inArrayCheck('Data A')

You forgot to go trough each value. You can also use find() function, to check if array have a value which sutisfy your condition.

Related

Javascript: How to compare a string against an array of strings [duplicate]

This question already has answers here:
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 2 years ago.
I want to be able to check if a string is equal to any of the strings inside an array. I know you can check multiple parameters like so:
let value = 'sales';
if ( value == 'sales' || value == 'broker' ){}
But I need to use an array like:
let value = 'sales';
let array = ['sales', 'broker'];
if ( value == array ){}
How can I do this?
Use array.includes:
if (array.includes(value)) {
...
}
You use array includes which returns a Boolean
let array = ['sales', 'broker'];
function test( value ) {
if ( array.includes(value) ){
console.log('true', value)
} else {
console.log('false', value)
}
}
test('sales')
test('world')
You can also use filter function, which might be better especially if you later need some additional checks.
if(array.filter(el => el === value).length > 0){
//
}
You can use includes method to check if array contains a value.
let array = ['sales', 'broker'];
console.log(array .includes('sales'));
use includes method
if (array.includes(value)) {
}

Comparing two Objects not working? [duplicate]

This question already has answers here:
How to determine equality for two JavaScript objects?
(82 answers)
Closed 4 years ago.
I'm facing an issue with comparing two Objects.
I'm comparing an incoming Object, with an Object Array,
to see if the Object is already in the array.
I tried two methods:
(betTemps is the Array of Objects, tempBet is the current object which should be compared.)
var duplicate = false;
for (let bet of this.betTemps) {
console.log(tempBet);
console.log(bet);
if(bet === tempBet) {
console.log("reached");
duplicate = true;
break;
}
}
The if afterwards:
.. else if(duplicate){
alert("The Bet is already in the List");
} ...
Console Output after adding an Object which is already in the Array:
Console Output Screenshot
As you can see, they are equal, still the other Object is added to the array.
I tried using this method too with indexOf:
if(this.betTemps.indexOf(tempBet) > -1){
alert("The Bet is already in the List");
}
Console Output after adding an Object which is already in the Array:
Console Output Screenshot
PS:
The code before the comparison:
addBet(bet, index){
var tempBet = Object.assign({}, bet);
var select = (document.getElementById('select'+index)) as HTMLSelectElement;
select = select.options as HTMLSelectElement;
let count = 0;
tempBet.category = [];
for(let i = 0; i < 3; i++) {
if (select[i].selected) {
tempBet.category.push(select[i].value):
count++;
}
}
The code after the comparison:
if (count == 0) {
alert("There has to be at least one Category choosen!");
} else if(duplicate <- This part changes individually which method you use ->){
alert("The Bet is already in the List");
} else {
this.betTemps.push(tempBet);
}
The best way to check if an object is in an array is using the array includes function:
Like if I want to check if A object is in B array I would check
(A === B.includes(A))

Using an empty object as a parameter to a conditional if loop [duplicate]

This question already has answers here:
How do I test for an empty JavaScript object?
(48 answers)
Closed 5 years ago.
This is similar to what I have been trying to do,
var obj = {};
if(obj){
//do something
}
What i want to do is that the condition should fail when the object is empty.
I tried using JSON.stringify(obj) but it still has curly braces('{}') within it.
You could use Object.keys and check the length of the array of the own keys.
function go(o) {
if (Object.keys(o).length) {
console.log(o.foo);
}
}
var obj = {};
go(obj);
obj.foo = 'bar';
go(obj);
You can check if the object is empty, i.e. it has no properties, using
Object.keys(obj).length === 0
Object.keys() returns all properties of the object in an array.
If the array is empty (.length === 0) it means the object is empty.
You can use Object.keys(myObj).length to find out the length of object to find if the object is empty.
working example
var myObj = {};
if(Object.keys(myObj).length>0){
// will not be called
console.log("hello");
}
myObj.test = 'test';
if(Object.keys(myObj).length>0){
console.log("will be called");
}
See details of Object.keys

Why is my return value undefined (JavaScript) [duplicate]

This question already has answers here:
Jquery each - Stop loop and return object
(6 answers)
Closed 9 years ago.
I have an array called questionSets full of objects. The createSet function should create new or create a copy of an existing questionSets object. The function getQuestionsFromSet is used if createSet is used to make a copy. For some reason when I call getQuestionsFromSet() from inside createSet() I always get a returned value of 'undefined'. I can't figure out why because when I do a console.log() of the value to be returned by getQuestionsFromSet() I see exactly what I want.
I have these two functions.
function createSet(name, copiedName) {
var questions = [];
if (copiedName) {
questions = getQuestionsFromSet(copiedName);
}
console.log(questions); // undefined. WHY??
questionSets.push({
label: name,
value: questions
});
}; // end createSet()
function getQuestionsFromSet(setName) {
$.each(questionSets, function (index, obj) {
if (obj.label == setName) {
console.log(obj.value); // array with some objects as values, which is what I expect.
return obj.value;
}
});
}; // end getQuestionsFromSet()
Because getQuestionsFromSet() does not return anything and so is implicitly undefined.
What you need is probably something like:
function getQuestionsFromSet(setName) {
var matched = []; // the array to store matched questions..
$.each(questionSets, function (index, obj) {
if (obj.label == setName) {
console.log(obj.value); // array with some objects as values, which is what I expect.
matched.push(obj.value); // push the matched ones
}
});
return matched; // **return** it
}
return obj.value; is nested within the inner $.each(function{}), and getQuestionsFromSet is indeed not returning anything.

How to check whether a given string is already present in an array or list in JavaScript? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Javascript - array.contains(obj)
Best way to find an item in a JavaScript Array ?
I want to check, for example, for the word "the" in a list or map. Is there is any kind of built in function for this?
In javascript you have Arrays (lists) and Objects (maps).
The literal versions of them look like this:
var mylist = [1,2,3]; // array
var mymap = { car: 'porche', hp: 300, seats: 2 }; // object
if you which to figure out if a value exists in an array, just loop over it:
for(var i=0,len=mylist.length;i<len;i++) {
if(mylist[i] == 2) {
//2 exists
break;
}
}
if you which to figure out if a map has a certain key or if it has a key with a certain value, all you have to do is access it like so:
if(mymap.seats !== undefined) {
//the key 'seats' exists in the object
}
if(mymap.seats == 2) {
//the key 'seats' exists in the object and has the value 2
}
Array.indexOf(element) returns -1 if element is not found, otherwise returns its index

Categories

Resources