Array Searching & Sorting in JavaScript
Last Updated :
29 Jul, 2025
Arrays in JavaScript often contain large sets of data like a list of numbers, names, or objects. To make the most of this data, you’ll frequently need to search for a specific item or sort items into a useful order.
Searching in Arrays
Array searching allows you to find specific elements within an array. Let’s explore two powerful methods to do this:
1. find()
The find() method returns the first element in an array that satisfies a provided testing function. It’s ideal for finding an object or value based on a condition.
Syntax
array.find(callback(element[, index[, array]])[, thisArg])
The callbackFunction accepts three arguments:
- currentValue: The current element being processed.
- index: The index of the current element.
- array: The array that find() was called on.
- thisArg (optional): Value to use as this in the callback.
Now let's understand this with the help of example
JavaScript
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
];
const user = users.find(user => user.id === 2);
console.log(user);
Output
{ id: 2, name: 'Bob' }
In this example
- Array users contains objects with id and name.
- find() is used to search for the user with id equal to 2.
- The callback checks if user.id === 2.
- It returns the first match, which is { id: 2, name: 'Bob' }.
2. findIndex()
The findIndex() method returns the index of the first element that satisfies the testing function, or -1 if no element is found.
Syntax
array.findIndex(callback(element[, index[, array]])[, thisArg])
In the above syntax
- findIndex(): Finds the index of the first element that satisfies the condition.
- callback: Checks each element in the array.
- Returns the index of the first match, or -1 if no match is found.
Now let's understand this with the help of example
JavaScript
const numbers = [10, 20, 30, 40];
const index = numbers.findIndex(num => num > 25);
console.log(index);
Output
2
In this example
- Array: numbers = [10, 20, 30, 40]
- findIndex(): Finds the index of the first number greater than 25.
- Callback: num => num > 25 checks each number.
- It returns the index of the first number that is greater than 25, which is 30 at index 2.
3. includes()
The includes() method checks if an array contains a specific value, returning true or false.
Syntax
array.includes(valueToFind[, fromIndex])
In the above syntax
- valueToFind: The value you're checking for.
- fromIndex (optional): Index to start the search from.
- Returns true if found, false if not.
Now let's understand this with the help of example
JavaScript
const fruits = ['apple', 'banana', 'orange'];
console.log(fruits.includes('banana'));
console.log(fruits.includes('grape'));
Output
true
false
In this example
- fruits.includes('banana'): Checks if 'banana' is in the array. Returns true.
- fruits.includes('grape'): Checks if 'grape' is in the array. Returns false.
4. indexOf()
The indexOf() method returns the first index of a specified value, or -1 if the value is not found.
Syntax
array.indexOf(searchElement[, fromIndex])
In the above syntax
- searchElement: The item you're searching for in the array.
- fromIndex (optional): The index to start the search from. Default is 0.
- The index of the first occurrence of searchElement.
- Returns -1 if the element is not found.
Now let's understand this with the help of example
JavaScript
const colors = ['red', 'blue', 'green', 'blue'];
console.log(colors.indexOf('blue'));
console.log(colors.indexOf('yellow'));
Output
1
-1
In this example
- colors.indexOf('blue'): Searches for 'blue' in the array. Returns 1 (first occurrence at index 1).
- colors.indexOf('yellow'): Searches for 'yellow' in the array.Returns -1 (not found).
Array Sorting in JavaScript
Just like searching helps retrieve data, sorting allows you to organize array elements to make them easier to read, compare, or manipulate. JavaScript’s primary method for sorting is sort(), with additional utilities like toSorted() (introduced in ES2023) for immutable sorting.
1. sort()
The sort() method sorts an array in place, modifying the original array. By default, it sorts elements as strings, but you can provide a comparison function for custom sorting.
Syntax
array.sort([compareFunction])
In the above syntax
- array.sort(): Sorts the elements of the array in place.
- compareFunction (optional): A function that defines the sort order. If not provided, the array elements are sorted as strings (lexicographically).
- Returns: The sorted array.
Now let's understand this with the help of example
JavaScript
const numbers = [100, 5, 20, 10];
numbers.sort((a, b) => a - b); // Ascending order
console.log(numbers);
In this example
- numbers.sort((a, b) => a - b): Sorts the numbers array in ascending order using the compareFunction (a, b) => a - b.
- Result: The array becomes [5, 10, 20, 100] after sorting.
- console.log(numbers): Logs the sorted array: [5, 10, 20, 100].
2. toSorted()
The toSorted() method (ES2023) returns a new sorted array, leaving the original array unchanged.
Syntax
array.toSorted([compareFunction])
In this syntax
- array.toSorted(): Creates a new sorted array without modifying the original array.
- compareFunction (optional): A function used to define the sort order. If not provided, it sorts in ascending order (as strings).
- Returns: A new array sorted based on the compareFunction.
Now let's understand this with the help of example
JavaScript
const numbers = [100, 5, 20, 10];
const sortedNumbers = numbers.toSorted((a, b) => a - b);
console.log(sortedNumbers);
console.log(numbers);
Output
[5, 10, 20, 100]
[100, 5, 20, 10]
In this example
- numbers.toSorted((a, b) => a - b): Sorts the numbers array in ascending order (from smallest to largest). Returns a new sorted array: [5, 10, 20, 100].
- console.log(sortedNumbers): Logs the sorted array: [5, 10, 20, 100].
- console.log(numbers): Logs the original array, which remains unchanged: [100, 5, 20, 10].
toSorted()
is a recent addition (ES2023) and may not be supported in older browsers.
Similar Reads
Web Development Technologies Web development refers to building, creating, and maintaining websites. It includes aspects such as web design, web publishing, web programming, and database management. It is the creation of an application that works over the internet, i.e., websites.Basics of Web Development : To better understand
7 min read
HTML Tutorial
CSS Tutorial CSS stands for Cascading Style Sheets. It is a stylesheet language used to style and enhance website presentation. CSS is one of the three main components of a webpage, along with HTML and JavaScript.HTML adds Structure to a web page.JavaScript adds logic to it and CSS makes it visually appealing or
7 min read
JS Tutorial
JavaScript TutorialJavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.Client Side: On the client side, JavaScript works
11 min read
JSON TutorialJSON (JavaScript Object Notation) is a widely-used, lightweight data format for representing structured data. Used Extensively : Used in APIs, configuration files, and data exchange between servers and clients.Text-based: JSON is a simple text format, making it lightweight and easy to transmit.Human
5 min read
TypeScript TutorialTypeScript is a superset of JavaScript that adds extra features like static typing, interfaces, enums, and more. Essentially, TypeScript is JavaScript with additional syntax for defining types, making it a powerful tool for building scalable and maintainable applications.Static typing allows you to
8 min read
Vue.js TutorialVue.js is a progressive JavaScript framework for building user interfaces. It stands out for its simplicity, seamless integration with other libraries, and reactive data binding.Built on JavaScript for flexible and component-based development.Supports declarative rendering, reactivity, and two-way d
4 min read
jQuery TutorialjQuery is a lightweight JavaScript library that simplifies the HTML DOM manipulating, event handling, and creating dynamic web experiences. The main purpose of jQuery is to simplify the usage of JavaScript on websites. jQuery achieves this by providing concise, single-line methods for complex JavaSc
8 min read
Front End
React TutorialReact is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
Angular TutorialAngular is a powerful, open-source web application framework for building dynamic and scalable single-page applications (SPAs). Developed by Google, Angular provides a comprehensive solution for front-end development with tools for routing, form handling, HTTP services, and more.Designed for buildin
4 min read
Backend
Node.js TutorialNode.js is a powerful, open-source, and cross-platform JavaScript runtime environment built on Chrome's V8 engine. It allows you to run JavaScript code outside the browser, making it ideal for building scalable server-side and networking applications.JavaScript was mainly used for frontend developme
4 min read
Express.js TutorialExpress.js is a minimal and flexible Node.js web application framework that provides a list of features for building web and mobile applications easily. It simplifies the development of server-side applications by offering an easy-to-use API for routing, middleware, and HTTP utilities.Built on Node.
4 min read
PHP TutorialPHP is a popular, open-source scripting language mainly used in web development. It runs on the server side and generates dynamic content that is displayed on a web application. PHP is easy to embed in HTML, and it allows developers to create interactive web pages and handle tasks like database mana
9 min read
Laravel TutorialLaravel is an open-source PHP web application framework that has gained immense popularity since its inception in 2011, created by Taylor Otwell. This renowned framework empowers developers to build robust, scalable web applications with remarkable ease. As a developer-friendly framework, Laravel of
3 min read
Database
Web Technologies Questions The following Web Technologies Questions section contains a wide collection of web-based questions. These questions are categorized based on the topics HTML, CSS, JavaScript, and many more. Each section contains a bulk of questions with multiple solutions. Table of Content HTML QuestionsCSS Question
15+ min read