JavaScript : Retrieve the keys or indices of array elements

Java Script @ Freshers.in

JavaScript arrays offer a plethora of methods for efficient manipulation and traversal. Among these, the keys() method is particularly useful for extracting array keys or indices. In this article, we’ll delve into the functionality of keys(), its syntax, functionality, and practical applications with detailed examples.

Understanding keys()

The keys() method in JavaScript returns a new Array Iterator object that contains the keys for each index in the array. It provides a convenient way to retrieve the keys or indices of array elements, facilitating iteration and manipulation.

Syntax

The syntax for keys() is straightforward:

array.keys();

Here, array represents the array for which the keys need to be retrieved.

Examples

Let’s explore various scenarios to understand the utility of keys():

Example 1: Basic Usage

const fruits = ['apple', 'banana', 'orange', 'grape'];
const keysIterator = fruits.keys();
console.log(keysIterator.next().value);
// Output: 0
console.log(keysIterator.next().value);
// Output: 1
console.log(keysIterator.next().value);
// Output: 2
console.log(keysIterator.next().value);
// Output: 3

Example 2: Iterating Over Keys

const nums = [10, 20, 30, 40];
for (const key of nums.keys()) {
  console.log(key);
}
// Output:
// 0
// 1
// 2
// 3

Example 3: Converting Keys to Array

const nums = [10, 20, 30, 40];
const keysArray = Array.from(nums.keys());
console.log(keysArray);
// Output: [0, 1, 2, 3]

The keys() method in JavaScript simplifies array key retrieval and iteration, providing a concise and efficient solution. Whether it’s extracting keys for manipulation or iterating over array indices, keys() streamlines the process with its simplicity and effectiveness.

Author: user