25-Aug-2022
.
Admin
Hello Dev,
This post will give you example of node js check if an array contains a given value. step by step explain check if an array contains a given value. you'll learn find if an array contains a given value node.js. you will learn node js given value if an array contains. Alright, let’s dive into the steps.
In this post, the example is node js check if an array contains a given value. Here, we’re using an array of users. The example is to check if a user with a given name exists in the list of users.
So, let's see the below solution with an example:
Install Node JS
This step is not required; however, if you have not created the node js app, then you may go ahead and execute the below command:
mkdir my-app
cd my-app
npm init
Exmple: 1
here, we need to create index.js file and add this code.
index.js
//create array list
users = [
{ id: 1, name: 'Piyush' },
{ id: 2, name: 'Keval' },
{ id: 3, name: 'Vivek' }
]
//find user in array list
contains = !!users.find(user => {
return user.name === 'Piyush'
})
console.log(contains);
Run Node JS App:
All the required steps have been done, now you have to type the given below command and hit enter to run the Node JS app:
node index.js
Output:
true
Exmple: 2
here, we need to create index.js file and add this code.
index.js
//create array list
users = [
{ id: 1, name: 'Piyush' },
{ id: 2, name: 'Vivek' },
{ id: 3, name: 'Mehul' }
]
//find user in array list
contains = !!users.find(user => {
return user.name === 'Keval'
})
console.log(contains);
Run Node JS App:
All the required steps have been done, now you have to type the given below command and hit enter to run the Node JS app:
node index.js
Output:
false
It will help you...
#Node JS