w3resource

JavaScript: Find if an array contains a specific element

JavaScript Array: Exercise-32 with Solution

Write a JavaScript function to find an array containing a specific element.

Test data:
arr = [2, 5, 9, 6];
console.log(contains(arr, 5));
[True]

Visual Presentation:

JavaScript: Find if an array contains a specific element

Sample Solution:

JavaScript Code:

// Function to check if an array contains a specific element
function contains(arr, element) {
    // Iterate through the array
    for (var i = 0; i < arr.length; i++) {
        // Check if the current element is equal to the target element
        if (arr[i] === element) {
            // Return true if the element is found in the array
            return true;
        }
    }
    // Return false if the element is not found in the array
    return false;
}

// Sample array
arr = [2, 5, 9, 6];

// Output the result of checking if the array contains the element '5'
console.log(contains(arr, 5));

Output:

true

Flowchart:

Flowchart: JavaScript: Find, if an array contains a specific element

ES6 Version:

// Function to check if an array contains a specific element
const contains = (arr, element) => {
    // Iterate through the array using the Array.prototype.some method
    return arr.some(item => item === element);
};

// Sample array
const arr = [2, 5, 9, 6];

// Output the result of checking if the array contains the element '5'
console.log(contains(arr, 5));

Live Demo:

See the Pen JavaScript - Find to if an array contains a specific element- array-ex- 32 by w3resource (@w3resource) on CodePen.


Contribute your code and comments through Disqus.

Previous: Write a JavaScript function to remove a specific element from an array.
Next: Write a JavaScript script to empty an array keeping the original.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/javascript-exercises/javascript-array-exercise-32.php