0

I have a user object as below and an array of location ids. I don't want the user.location_id to be equal to any value in the location_ids array stated as below using Javascript. Please help me achieve it.

user: {
  first_name: 'James',
  last_name: 'Smith',
  location_id: 21
},

location_ids:[23, 31, 16, 11]

So I want to

if (user.location_id != any value in the locations_ids array) {
 console.log("Select User")
}

Help me achieve this using javascript

1
  • 1
    if (!location_ids.includes(user.location_id)) { console.log("Select user"); } Commented May 25, 2021 at 15:52

2 Answers 2

3

You can use the includes method to find if the element is present in the array or not.

The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate. - MDN

if(!location_ids.includes(user.location_id)){}

const user = {
  first_name: "James",
  last_name: "Smith",
  location_id: 21,
};
const location_ids = [23, 31, 16, 11];

if (!location_ids.includes(user.location_id)) {
  console.log("Select user");
}

// Change location ID
user.location_id = 11;

if (!location_ids.includes(user.location_id)) {
  console.log("Select user");
} else {
  console.log("Don't select user");
}

Sign up to request clarification or add additional context in comments.

3 Comments

OP does not want the user.location_id in the array so you should negate the includes result.
Thank you @decpk, great finding mate.
It is better to explain how your answer solved OP's problem....
0

Here's [a link] (https://techfunda.com/howto/729/not-equal-operator)

Here's [a link] (https://techfunda.com/howto/929/array-indexof-search)

 
    function myFunction() {
        var a = ["France", "Nritian", "Israel", "Bhutan", "US", "UK"];
        var b = a.indexOf("Africa");
        document.getElementById("myId").innerHTML = b;
    }
 
<!DOCTYPE html>
<html>
    <head>
        <title>Demo</title>
    </head>
<body>
    <p>Click the below button to know the output for an search which is not presented in an array.</p>
<input type="button", onclick="myFunction()" value="Find"/>
<p id="myId"></p>


</body>
</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.