Array extensions
The array extensions Array.of()
, Array.from()
, Array.find()
, and Array.findIndex()
are all introduced in ES6 (ECMAScript 2015) and provide useful functionality for working with arrays. Here's an explanation of each with code examples:
Array.of():
The Array.of()
method creates a new array instance from a variable number of arguments, regardless of the number or type of the arguments.
const arr = Array.of(1, 2, 3, 4, 5);
console.log(arr); // Output: [1, 2, 3, 4, 5]
Array.from():
The Array.from()
method creates a new, shallow-copied array instance from an array-like or iterable object, such as an array, string, or set.
const str = 'hello';
const arr = Array.from(str);
console.log(arr); // Output: ['h', 'e', 'l', 'l', 'o']
Array.find():
The Array.find()
method returns the value of the first element in the array that satisfies the provided testing function. Otherwise, it returns undefined
.
const numbers = [10, 20, 30, 40, 50];
const found = numbers.find(num => num > 25);
console.log(found); // Output: 30
Array.findIndex():
The Array.findIndex()
method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1
.
const numbers = [10, 20, 30, 40, 50];
const index = numbers.findIndex(num => num > 25);
console.log(index); // Output: 2 (index of 30)
Code Example:
// Using Array.of()
const arr1 = Array.of(1, 2, 3);
console.log(arr1); // Output: [1, 2, 3]
// Using Array.from()
const str = 'hello';
const arr2 = Array.from(str);
console.log(arr2); // Output: ['h', 'e', 'l', 'l', 'o']
// Using Array.find()
const numbers = [10, 20, 30, 40, 50];
const foundValue = numbers.find(num => num > 25);
console.log(foundValue); // Output: 30
// Using Array.findIndex()
const index = numbers.findIndex(num => num > 25);
console.log(index); // Output: 2 (index of 30)
These array extensions provide convenient methods for creating and working with arrays, enabling cleaner and more concise code for common array operations such as creating arrays from various sources and searching for specific elements.
Leave a Comment