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

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)) {
}

Related

Check if value exists in array javascript [duplicate]

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.

Return subset of JSON Object using Javascript map() function

My question is if there is a simple way to return a subset of JSON object that will contain all 'columns' rather than specifying individually which 'columns' to return.
In particular, I have a multi-column csv file converted to JSON. The function below returns a subset of that object - just two 'columns' (as another object) if certain condition is met (in this case 'Name' is matched):
var firstSubArr = json.map(function(s) {
if (s.Name === RegName) {
return {
'Price': s.Price,
'Name': s.Name
}
}
}).filter(function(n) {
return n !== undefined
});
Is there a simpler way to return "all columns" from json object as object rather that this:
return {'Price':s.Price,'Name':s.Name}?
Comment:
It is just a simple JSON structure after conversion from csv, eg:
`[
{Name:'Sydney', Price:123, Type:'xyz', etc. 20 more... },
etc.
]`
Comment 2: Yes filter may be an option as a couple of people suggested but what if my condition is a bit more complex, like:
var fullPeriodArr= json.map( function (s) {
if(moment(s.Date,"YYYYMMDD").isSameOrBefore(currd) && moment(s.Date,"YYYYMMDD").isSameOrAfter(fullPeriodStart) && (s.Type==sid || s.Type==sid2)&& s.Name===RegName){return [s.Price, s.Name]
}
}).filter( function (n) {
return n!== undefined
});
SOLUTION:
All 3 respondents provided the clue, thanks! It was just “return every object in the array of objects that matches the condition”, or simply:
var firstSubArr= json.filter(
s => (moment(s.Date,"YYYYMMDD").isSameOrBefore(currd) && moment(s.Date,"YYYYMMDD").isSameOrAfter(fullPeriodStart) && (s.Type==sid || s.Type==sid2) && s.Name===RegName)
);
. where time range 'from... to' is evaluated using moment.js lib and Date, Type and Name are object keys.
The secret pudding was the round bracket ( ) around the complex condition.
How neat Javascript has become: no need to get .length nor to loop with 'for' or 'while', no 'if... else' statements, or no need to store interim results, and no 'return'. The arrow replaces all that!
Then you can access eg. Price 'column' as array of numbers for summary calculations (eg. sum of values):
var firstSubArrPrice=firstSubArr.map(t => t.Price );
Get rid of the map() and just use filter() and you will have the original objects in resultant
var firstSubArr = json.filter(function(s) {
return s.Name === RegName
});
I understood that you want to return the the object with specific properties which matches the condition.You can do that using reduce()
var firstSubArr = json.reduce((ac,{Name,Price}) => a.Name === RegName ? [...ac,{Name,Price}] : ac, []);
If you don't want only Name,Price and all properties with calling names. Then use filter() alone
var firstSubArr = json.filter(x => x.Name === RegName)
How about:
var firstSubArr = json.filter( x => x.Name ===RegName)
To make it in JavaScript I recommend this code:
var valueNeedly = json.filter(function(s) {
return s.value === searchValue
});

How to calculate the number of objects I get from the loop Javascript

I filtered my set of users(array) with if(elem.id_verified). I now get 77 users objecta. I just want to take the number of these objects. I tried with console.log(this.numOfunverifiedUsers.length) but i get 77 underfined. My question is how to assemble all objects and get that number. Maybe my logic is going in the wrong direction.
this.users=response.data.users
this.numOfunverifiedUsers = []
this.users.forEach(elem => {
if (elem.id_verified === 0) {
this.numOfunverifiedUsers = elem
console.log(this.numOfunverifiedUsers.length)
}
})
this.numOfunverifiedUsers.push(elem)
Push the element in array.
this.numOfunverifiedUsers = elem , replace it with above
This should work too:
console.log(this.users.filter(function (val) {
return val.id_verified === 0
}).length)
filter items that are id_verified === 0 and count their length.
I think would be better you build that list with a filter:
this.numOfunverifiedUsers = this.users.filter(
user => user.id_verified === 0
);
console.log(this.numOfunverifiedUsers);
console.log(this.numOfunverifiedUsers.length);
If you want to read about filter: Filter method
With this.numOfunverifiedUsers = elem, you are assigning 'elem' to an array reference. As a result, you get exceptions which make the '=' operator return the undefined primitive type (as the result of function errors; see undefined - JavaScript | MDN). What you want to do is either add the element iteratively into the array the "old way", via element assigning, or just use the OOP way via the push method. The former wouldn't require a count function, as you can do something like that:
var count = 0; //outside the forEach
...
if (elem.id_verified === 0) {
{
this.numOfunverifiedUsers[count++]=elem
console.log(count)
}
...
However, as others pointed out, using a filter makes the code much more clean and readable
This would work better with the use of a Filter
console.log(this.users.filter(function (val) {
return val.id_verified === 0
}).length)
filter items that are id_verified === 0 and count their length.

How to check if value existed in array or not?

I dont want to push duplicate values into selectedOwners, so in below code user is selecting owner if owner already existed in selectedOwners array i dont want to push , How can i check that to avoid duplicate values in an array ?
ctrl.js
var selectedOwners = [];
$scope.addProcessOwner = function(dataItem){
var selectedOwner = {
fullName: dataItem.fullName,
workerKey: dataItem.workerKey
}
if(selectedOwners.indexOf(selectedOwner) !== -1) {
selectedOwners.push(selectedOwner);
}
console.log('WORKER DATA',selectedOwners);
}
You can use Array.prototype.some method
The some() method tests whether some element in the array passes the test implemented by the provided function.
var isExists = function(e) {
if (e.fullName == selectedOwner.fullName
&& e.workerKey == selectedOwner.workerKey) {
return true;
}
}
if (!selectedOwners.some(isExists)) {
selectedOwners.push(selectedOwner);
}
The use of Array.indexOf is obvious for simple types like strings and numbers.
However, when you are looking for an object, you have to pass the exact same object. A different object with all the same properties and values will still not work. Think of the array as containing pointers to the objects and you must look for the same pointer.
Instead you will need to write your own method to compare the owners for equality and loop through the array doing this check.
Try wrapping your "if" logic in a for-loop .
Example
//Following code loops through array and check for already existing value
for(var i = 0; i < selectedOwners.length; i++){
if(selectedOwners.indexOf(selectedOwner) !== -1) {
selectedOwners.push(selectedOwner);
}
}

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