Array methods

A JavaScript Array is an ordered collection of values, each identified by a numeric index. The values in a JavaScript array can be of different data types, including numbers, strings, booleans, objects, and even other arrays. Arrays are contiguous in memory, which means that all elements are stored in a single, continuous block of memory locations, allowing for efficient indexing and fast access to elements by their index.

Returns a single value

Higher order functions

The reduce() method of method of Array instances executes a callback function on each element of the array, in order,  passing in the return value from the calculation on the preceding element.

This is a valid solution. Function iterates over the array using for loop and adds each element to the sum variable:

const array = [5, 1, 3, 2, 6];

// sum or max
function findSum(array) {
	let sum = 0;
	for (let i = 0; i < array.lenght; i++) {
		sum = sum + arr[i]
	}
	return sum;
}
console.log(findSum(array));
// expected output: 17

There is a solution more efficient with reduce because we apply the addition to each element of the array:

const output = array.reduce(function(accumulator, current) {
	accumulator = accumulator + current;
	return accumulator;
}, 0); // initial value
console.log(output);
// expected output: 17

Or with arrow function syntax:

function sumArray(array) {
	return array.reduce((accumulator, current) => accumulator + current, 0);
}
console.log(output);
// expected output: 17

Returns a Boolean

find()

The find() method of Array instances returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

const array = [1, 3, 12, 144, 20]
const found = array.find((el) => el > 10);
console.log(found)
// expected output: {found: 12}

includes()

The includes() method of Array instances determines whether an array includes a certain value among its entries, returning true or false as appropriate.

const array = [1, 2, 3];

console.log(array.includes(2));
// Expected output: true

Without mutation

concat()

This method creates a new array by merging two or more arrays. When used with a single array, it effectively creates a  shallow copy.

const beatlesArray = ["Paul", "John", "George", "Ringo"];
const fifthBeatleArray = beatlesArray.concat("Billy Preston");

console.log(fifthBeatleArray); // ["Paul", "John", "George", "Ringo", "Billy Preston"]
console.log(fiftBeatleArray === beatlesArray); // false

filter()

Higher order functions

The filter() method of Array instances creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.

Note

filter() always returns a new instance, even if it results in not filtering out any values.

const words = ["spray", "elite", "exuberant", "destruction", "present"];

const result = words.filter((word) => word.length > 6);

console.log({result});
// Expected output: Array ['exuberant', 'destruction', 'present']

map()

Higher order functions

The map() method creates a new array with the results of the specified function call applied to each of its elements.

const numbers =
function doubleEven(nums: number[]): number[] {
  return nums.filter((num) => num % 2 === 0 ).map((num) => num * 2);
}
console.log(doubleEven([1, 2, 3, 4, 5, 6, 7, 8]));
// Expected output: [4, 8, 12, 16]

slice()

The slice() method of Array instances returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.

const animals = ["ant", "bison", "camel", "duck", "elephant"];
const newAnimalsArray = animals.slice(2); 

console.log(newAnimalsArray);
// Expected output: Array ['camel', 'duck', 'elephant']
Note

slice() without arguments returns a copy of the entire array.

Mutates the original array

splice()

The splice() method in JavaScript is a powerful way for modifying arrays. It allows you to add or remove elements from any position in an array, including the middle. The return value for the splice() method will be an array of the items removed from the array. If nothing was removed, then an empty array will be returned.

let fruits = ["apple", "banana", "orange", "mango", "kiwi"];
let removed = fruits.splice(2, 2);

console.log(fruits);  // ["apple", "banana", "kiwi"]
console.log(removed); // ["orange", "mango"]

If you need to keep the original array unchanged, you should create a copy before using splice():

let original = [1, 2, 3, 4, 5];
let copy = [...original];
copy.splice(2, 1, 6);

console.log(original); // [1, 2, 3, 4, 5]
console.log(copy);     // [1, 2, 6, 4, 5]
Powered by Forestry.md