Not contains in array javascript

JavaScript: Check if Array Contains a Value/Element

Arrays are one of the most widely used data structures in Computer Science. While dealing with a list of items (array), we are often required to look for a particular value in the list. JavaScript contains a few built-in methods to check whether an array has a specific value, or object.

In this article, we’ll take a look at how to check if an array includes/contains a value or element in JavaScript.

Check Array of Primitive Values Includes a Value

Array.includes() Function

The simplest way to check for a primitive value in an array is to use the includes() method:

let isInArray = arr.includes(valueToFind[, fromIndex]) // arr - array we're inspecting // valueToFind - value we're looking for // fromIndex - index from which the search will start (defaults to 0 if left out) // isInArray - boolean value which tells us if array contains valueToFind 

For example, let’s check whether the array of animals contains the dog and cat emojis:

let animals = ["🐘", "🐒", "🐶", "🐍"] animals.includes("🐶") // true animals.includes("🐱") // false 

The function returns a boolean value, signifying the value’s presence or lack thereof.

Array.indexOf() Function

In cases where we need the exact location of the element we’re looking for, we can use the indexOf(elem) method, which looks for elem in the specified array and returns the index of its first occurrence, and -1 if the array does not contain elem .

Читайте также:  Idea java project with gradle

For example, we can look for the first occurrence of a grade in an array containing grades:

let grades = ["B", "D", "C", "A"] grades.indexOf("A") // 3 grades.indexOf("F") // -1 

In the first instance, the element is present, and its position is returned. In the second instance, the return value signifies that the element is not present.

We can use this to alter code flow easily:

let grades = ["B", "D", "C", "A"] if (grades.indexOf("F") >= 0) < console.log("Element is present"); > else < console.log("Element is not present"); > 

If we pass in F , the adequate message is printed:

Checking if Array of Objects Includes Object

some() Function

When searching for an object, includes() checks whether the provided object reference matches the one in the array. This is rarely what we want, because objects can have identical fields with corresponding values but different references.

We can use the some() method to search by object’s contents. The some() method takes one argument and accepts a callback, which is executed once for each value in the array until it finds an element which meets the condition set by the callback function, and returns true .

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Let’s look at some() in action to understand it better:

let animals = [name: "dog">, name: "snake">, name: "monkey">, name: "donkey">] let element = name: "monkey"> animals.some(animal => animal.name === element.name) 

The callback function returns false for the first two cases, but returns true for the third element, as the names match. After this, some() halts execution and returns true .

Conclusion

In this article, we’ve gone over the few ways to check whether an array contains a value or not, in JavaScript.

We’ve covered the includes() function, which returns a boolean value if the value is present. The indexOf() function returns the index of a value if it’s present, and -1 if it isn’t.

Finally, for objects, the some() function helps us search for object presence based on their contents.

Источник

Not contains in array javascript

Last updated: Dec 26, 2022
Reading time · 4 min

banner

# Table of Contents

# Check if Array Doesn’t contain a Value in JavaScript

Use the logical NOT (!) operator to negate the call to the includes() method to check if an array doesn’t contain a value.

The negated call to the Array.includes() method will return true if the value is not in the array and false otherwise.

Copied!
const arr = ['a', 'b', 'c']; const notIncludesD = !arr.includes('d'); console.log(notIncludesD); // 👉️ true const notIncludesC = !arr.includes('c'); console.log(notIncludesC); // 👉️ false if (notIncludesC) console.log('✅ the value c is NOT contained in the array'); > else // 👇️ this runs console.log('⛔️ the value c is contained in the array'); > // --------------------------------------- // ✅ Check if an object is not contained in an array const arr2 = [id: 1>, id: 2>, id: 3>]; const notContained = arr2.every(obj => return obj.id !== 4; >); console.log(notContained); // 👉️ true

We used the logical NOT (!) operator to negate the calls to the Array.includes() method.

This approach allows us to check if a specific value is not contained in the array.

Our first example checks if the value d is not contained in the array and returns true .

Copied!
const arr = ['a', 'b', 'c']; const notIncludesD = !arr.includes('d'); console.log(notIncludesD); // 👉️ true const notIncludesC = !arr.includes('c'); console.log(notIncludesC); // 👉️ false

The string c is contained in the array, so the expression returns false .

Here are some more examples of using the logical NOT (!) operator.

Copied!
console.log(!true); // 👉️ false console.log(!false); // 👉️ true console.log(!'hello'); // 👉️ false console.log(!''); // 👉️ true console.log(!null); // 👉️ true

You can imagine that the logical NOT (!) operator first converts the value to a boolean and then flips the value.

The falsy values in JavaScript are: null , undefined , empty string, NaN , 0 and false .

If you have to perform the test often, define a reusable function.

Copied!
function notIncludes(array, value) return !array.includes(value); > const arr = ['a', 'b', 'c']; console.log(notIncludes(arr, 'c')); // 👉️ false console.log(notIncludes(arr, 'd')); // 👉️ true console.log(notIncludes(arr, 'z')); // 👉️ true

The notIncludes() function takes an array and a value as parameters and checks if the value is not contained in the array.

The function returns true if the value is not contained in the array and false otherwise.

You can also use the indexOf() method to check if a value is not contained in an array.

# Check if Array Doesn’t contain a Value using indexOf()

This is a two-step process:

  1. Use the indexOf() method to get the index of the value in the array.
  2. If the method returns -1 , the array doesn’t contain the value.
Copied!
const arr = ['a', 'b', 'c']; if (arr.indexOf('d') === -1) // 👇️ this runs console.log('The value d is NOT contained in the array'); > else console.log('The value d is contained in the array'); > console.log(arr.indexOf('c')); // 👉️ 2 console.log(arr.indexOf('z')); // 👉️ -1

The Array.indexOf method returns the index of the first occurrence of the supplied value in the array.

If the value is not contained in the array, the method returns -1 .

Our if statement checks if the Array.indexOf() method returned -1 .

If you have to perform the test often, define a reusable function.

Copied!
function notIncludes(array, value) return array.indexOf(value) === -1; > const arr = ['a', 'b', 'c']; console.log(notIncludes(arr, 'c')); // 👉️ false console.log(notIncludes(arr, 'd')); // 👉️ true console.log(notIncludes(arr, 'z')); // 👉️ true

The function takes an array and a value as parameters and returns true if the value is not contained in the array.

If you need to check if an object is not contained in an array, use the Array.every() method.

# Check if an object is not contained in an array in JavaScript

To check if an object is not contained in an array:

  1. Use the Array.every() method to iterate over the array.
  2. Check if each object doesn’t have a property equal to the specific value.
  3. The every() method will return true if the object is not in the array.
Copied!
const arr2 = [id: 1>, id: 2>, id: 3>]; const notContained = arr2.every(obj => return obj.id !== 4; >); console.log(notContained); // 👉️ true if (notContained) console.log('The object is NOT contained in the array'); > else console.log('The object is contained in the array'); >

The function we passed to the Array.every method gets called with each element of the array.

If all invocations of the callback function return a truthy value, then the Array.every() method returns true , otherwise, false is returned.

On each iteration, we check if the current object doesn’t have a specific value and return the result.

If the callback function we passed to the Array.every() method returns a falsy value, then Array.every() short-circuits also returning false .

If the Array.every() method returns true , then the object isn’t contained in the array.

If the method returns false , the object is contained in the array.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью