The Wayback Machine - https://web.archive.org/web/20240903194437/https://www.geeksforgeeks.org/different-ways-to-search-an-item-in-an-array-in-javascript/
Open In App

Different ways to search an item in an array in JavaScript

Last Updated : 04 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Searching for an item in a JavaScript array involves determining whether a specific element is present within the array. This process is fundamental for tasks like data validation, filtering, and manipulation, enabling developers to locate and manage elements within arrays in their applications efficiently.

These are the following methods:

Using find() method

The Javascript arr.find() method is used to get the value of the first element in the array that satisfies the provided condition. It checks all the elements of an array and whichever the first element satisfies the condition is going to print. This function will not work having the empty array elements and also does not change the original array.

Syntax:

array.find(function(currentValue, index, arr), thisValue);

Example: In this example, we will use the Javascript Array find() method to search for an element in an array. This method searches for the first element that is greater than 50 and returns it.

JavaScript
const arr = [25, 33, 22, 45, 67, 1, 32, 223];

const greaterElement = arr.find(ele => ele > 50);

console.log(greaterElement);

Output
67

Using findIndex() method

The Javascript Array.findIndex() method is used to return the first index of the element in a given array that satisfies the provided testing function (passed in by the user while calling). Otherwise, if no data is found then the value of -1 is returned.

Syntax:

array.findIndex(function(currentValue, index, arr), thisValue);

Example: This example returns the index of the first element that is greater than 50.

JavaScript
const arr = [25, 33, 22, 45, 67, 1, 32, 223];

let greaterElement = arr.findIndex(ele => ele > 50);

console.log(greaterElement);

Output
4

Using includes() method

The Javascript array.includes() method is used to know whether a particular element is present in the array or not and accordingly, it returns true or false i.e., if the element is present, then it returns true otherwise false.

Syntax:

array.includes(searchElement, start);

Example: This example shows the use of the array includes() method in Javascript.

JavaScript
const arr = ['Geeks','for','geeks','Javascript','HTML','CSS']

console.log(arr.includes('geeks'));
console.log(arr.includes('Javascript'));
console.log(arr.includes('CSS'));
console.log(arr.includes('React'));

Output
true
true
true
false

Using some() method

The Javascript arr.some() method checks whether at least one of the elements of the array satisfies the condition checked by the argument method.

Syntax:

arr.some(callback(element,index,array),thisArg);

Example: In this example, we will check for some elements in the array that are greater than 50 or not. The function returns true as there are elements greater than 50 in the array.

JavaScript
const arr = [25, 33, 22, 45, 67, 1, 32, 223];

console.log(arr.some((element) => element > 50));
console.log(arr.some((element) => element < 40));
console.log(arr.some((element) => element > 70));

Output
true
true
true

Using indexOf() method

The JavaScript Array indexOf() Method is used to find the index of the first occurrence of the search element provided as the argument to the method.

Syntax:

array.indexOf(element, start);

Example: This example shows the use of the array indexOf() method in JavaScript

JavaScript
const arr = ['Geeks','for','geeks','Javascript','HTML','CSS']

console.log(arr.indexOf('Geeks'));
console.log(arr.indexOf('HTML'));
console.log(arr.indexOf('React'));

Output
0
4
-1

Using filter() method

The JavaScript Array filter() Method is used to create a new array from a given array consisting of only those elements from the given array which satisfy a condition set by the argument method.

Syntax:

array.filter(callback(element, index, arr), thisValue);

Example: This example checks for elements greater than 50 in an array using the Array filter() method.

JavaScript
const arr = [25,33,22,45,67,81,32,223];
const greaterElement = arr.filter(ele => ele > 50);

console.log(greaterElement)

Output
[ 67, 81, 223 ]

Using every() method

  • In this approach, we will Initialize the test list. 
  • Use every method which checks the opposite of the condition we want to check if all element satisfies the condition every return True else return False. 
  • Print result. 

Syntax:

arr.every(callback(element,index,array),thisArg);

Example: This example shows the useful of every() method.

JavaScript
const arr = [25, 33, 22, 45, 67, 1, 32, 223];

console.log(!arr.every((element) => element < 50));
console.log(!arr.every((element) => element > 40));
console.log(!arr.every((element) => element < 70));

Output
true
true
true


Similar Reads

Different ways to delete an item from an array using JavaScript
In Javascript, we do not have any array.remove() method for deleting the element. we will have an array and we need to delete a given item from that array and return the resulting array in the console. These are the following methods for solving this problem: Table of Content Using for loop and push() MethodUsing Pop() MethodUsing shift() MethodUsi
4 min read
Different Ways to Use Array Slice in JavaScript
In this article, we will see the different ways to use the Array slice method in Javascript. Using Array Slice in JavaScript refers to the technique of extracting a specified portion of an array, defined by start and end indices, to create a new array containing those selected elements. Syntaxarr.slice(begin, end);Parameters: This method accepts tw
3 min read
Different Ways to Crate an Array of Objects in JavaScript ?
Objects in JavaScript are key-value pairs, making them suitable for representing structured data. Also, an array in JavaScript is a versatile data structure that can hold a collection of values. When dealing with objects, an array can be used to store multiple objects. An array of objects allows you to organize and manage multiple sets of related i
3 min read
Different ways to populate an array in JavaScript
Populating an array in JavaScript means initializing it with elements. This could involve adding values manually, dynamically generating values using loops or functions, or copying elements from another array. It's a fundamental operation for creating and manipulating arrays in JavaScript programs. These are the following ways to populate an array:
5 min read
Count Frequency of an Array Item in JavaScript
In this article, we will be counting the frequency of an array item in Javascript. When working with arrays there are situations when we need to count the frequency of an array item. Javascript provides us with some methods to count the occurrences of an item in an array, some of them are explained below: Using for loopUsing filter() methodUsing re
3 min read
How to Remove a Specific Item from an Array in JavaScript ?
To remove a specific item from an array, it means we have given an array with a number n and we have to remove the element present at index n. In this article, we are going to learn how to remove a specific item from an array in JavaScript. Below are the approaches to remove a specific item from an array in JavaScript: Table of Content Using splice
4 min read
Get the first and last item in an array using JavaScript
JavaScript array is used to store multiple elements in a single variable. It is often used when we want to store a list of elements and access them by a single variable. We will learn how to get the first &amp; last element in an array in JavaScript, along with understanding their implementation through the examples. These are the following approac
5 min read
Best Way to Find an Item in an Array in JavaScript
In JavaScript, an array is a collection of elements that can hold different data types. There are various ways to check if a specific item is present in an array. In this article, we will see the possible techniques to find the item in a given array in JavaScript. The most commonly used methods to find if an item is in a JavaScript array are: Table
8 min read
How to Splice Duplicate Item from JavaScript Array?
Given an array of numbers or strings containing some duplicate values, the task is to remove these duplicate values from the array without creating a new array or storing the duplicate values anywhere else. Examples: Input: arr = [1, 2, 3, 4, 3, 2, 1];Output: [1,2,3,4]Input: [1, 4, 6, 1, 2, 5, 2, 1, 6, 8, 7, 5];Output: [4, 1, 5, 2, 6, 8, 7]Table of
4 min read
How to replace an item from an array in JavaScript ?
Replacing an item from an array in JavaScript refers to the process of updating the value of an existing element at a specified index within the array with a new value, effectively modifying the array content. Examples of replacing an item from an array in JavaScript Table of Content Using Array IndexingUsing the splice() MethodUsing array map() an
5 min read
Remove the last Item From an Array in JavaScript
Removing the last item from an array in JavaScript is a fundamental operation often encountered in array manipulation tasks. It involves eliminating the last element of an array, which can be useful for dynamically adjusting array contents based on various conditions or requirements within a program. Methods to Remove the Last Element from an Array
5 min read
How to insert an Item into Array at Specific Index in JavaScript?
To insert an item into the array at a specific index we will break the array from the index and insert the item into the array. There is no inbuilt method in JavaScript that directly allows for the insertion of an element at any arbitrary index of an array. The possible approaches are given below. Let's create a JavaScript program having an array,
6 min read
Different Ways to Abort JavaScript Execution
Aborting JavaScript execution can help us to write more robust, secure, and efficient code by preventing unexpected errors and behaviors. Possible reasons why we need to abort JavaScript execution are:We might need to abort execution when an error occurs to prevent further execution of the code and avoid unexpected behavior or data corruption.We mi
5 min read
Different ways to access HTML elements using JavaScript
Sometimes, users need to manipulate the HTML element without changing the code of the HTML. In this scenario, users can use JavaScript to change HTML elements without overwriting them. Before we move ahead to change the HTML element using JavaScript, users should learn to access it from the DOM (Document Object Model). Here, the DOM is the structur
7 min read
Different ways of writing functions in JavaScript
JavaScript Function is a block of code that is designed to perform a task and executed when it is been called or invoked. Below are the ways of writing functions in JavaScript: Table of Content Function DeclarationFunction ExpressionArrow FunctionsFunction DeclarationFunction Declaration is the traditional way to define a function. It is somehow si
2 min read
How to declare variables in different ways in JavaScript?
In JavaScript, variables can be declared using keywords like var, let, or const, each keyword is used in some specific conditions. Understanding these declarations is crucial for managing variable lifetimes and avoiding unintended side effects in code. Table of Content JavaScript varJavaScript letJavaScript const Difference Between var, let, and co
2 min read
How to add default search text to search box in HTML with JavaScript ?
We can add a default search text to the search box by using the JavaScript DOM getElementById() method and the onfocus &amp; onblur events. getElementById(): The DOM getElementById() method is used to return values to the unique id of the input tag used in HTML. It is one of the most widely used DOM HTML methods when we want to manipulate and get i
3 min read
How to get the last item of JavaScript object ?
In this article, we will learn how to get the last item of a Javascript object. Given a JavaScript object and the task is to get the last element of the JavaScript object. This can be done by the following methods: Using Object.keys() methodUsing for loopmethodApproach 1: Use Object.keys() method to get the all keys of the object.Now use indexing t
2 min read
How to Find if Two Arrays Contain any Common Item in JavaScript?
JavaScript Array is a single variable that is used to store elements of different data types. JavaScript arrays are zero-indexed. So, we are given two arrays containing array elements and the task is to check if two arrays contain any common elements then it returns True otherwise returns False. Examples: Input: array1 = ['a', 'b', 'c', 'd', 'e'] a
7 min read
How to delete an item or object from the array using ng-click ?
The task is to delete the item from the list when the button is clicked. This all should be done by using ng-click. This is done by using the splice() method. The syntax for the method is given below. Syntax for splice() function: array.splice(indexno, noofitems(n), item-1, item-2, ..., item-n) Example for splice() function: const topics = ['Array'
2 min read
How to Push Item From an Array in Mongoose ?
In Mongoose, pushing an item to an array can be done using different approaches. To push an item into an array, you can use the $push operator along with the updateOne() or updateMany() method. We will discuss the different methods to push items from an array in Mongoose: Table of Content Inserting a new document Using $push OperatorUsing addToSet
4 min read
How to Pull Item from an Array in Mongoose ?
In Mongoose, pulling an item from an array can be done using several methods. To pull an item from an array, you can use the $pull operator along with the updateOne() or updateMany() method. We will discuss the different methods to pull items from an array in Mongoose Table of Content Using $pull OperatorPull Based on a ConditionPull from Nested Ar
4 min read
How to Add a Number to Every Item in an Array?
Adding a number to every item in an array is a common operation in JavaScript, often required for tasks like incrementing values or performing mathematical operations on array elements. Below are the approaches to add a number to every item in an array: Table of Content Using Array.map() MethodUsing a for LoopUsing reduce MethodUsing forEach() Meth
3 min read
Remove an Item from Array using UnderscoreJS
Underscore.js is a JavaScript library that provides a wide range of utility functions for working with arrays, objects, functions, and more. One common task when working with arrays is removing an item based on a specific condition. In this article, we will explore options to remove an item from an array using Underscore.js. Table of Content Using
2 min read
How do I Remove an Array Item in TypeScript?
In this article, we will learn about the different ways of removing an item from an array in TypeScript. In TypeScript, an array can be defined using union typing if it contains items of different types. We can use the following methods to remove items from a TypeScript array: Table of Content Using the splice() methodUsing the shift() methodUsing
5 min read
How to remove an item from an array in AngularJS Scope?
In the AngularJS framework, we can manipulate the data that is within the scope, for example, we can perform the operations on an array by removing its elements. This helps us for better efficiency in developing the web application. We can remove the array elements in the applications like to-do list items, or the application that is used to displa
6 min read
How To Delete An Item From State Array in ReactJS?
It is important to manage the state in ReactJS for building interactive user interfaces. Sometimes when we work with arrays, we need to remove an item from these arrays. A common use case is deleting an item from an array stored in the component’s state. In this article, we’ll explore different ways to handle this operation in ReactJS. Below are di
3 min read
How to Sort an Array using JavaScript when Array Elements has Different Data Types ?
Sorting an array in JavaScript is the process of arranging the elements of the array in a certain order. Generally sorting in an array is to arrange the elements in increasing or decreasing order. It is a common task, however, when an array contains different data types such as numbers, strings, and booleans, sorting becomes a little more complicat
3 min read
Different ways for passing data to view in Laravel
Laravel provides different ways to pass data to a view. We can pass data directly from routes or through the controller. Here are some of the ways we can pass data to the view: Using view() Using with() Using compact() Using Controller Class 1. Using view(): We can directly pass the data in the ‘view()’ helper function by using the second parameter
5 min read
Different ways to Improve Website Navigation
In the digital world, everyone knows how important websites are for the growth of the business. It is the best way to market one’s business online. If you do not have any website, then are chances that you might lose good opportunities for business even you cannot reach more audience or users. Therefore, the website is really important to establish
4 min read