Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
0 views

Array Methods Summary

The document provides a comprehensive overview of JavaScript array methods, including basic methods such as length, toString(), at(), join(), pop(), and push(). It also covers more advanced methods like concat(), copyWithin(), flat(), splice(), toSpliced(), and slice(), along with examples demonstrating their usage. Additionally, it highlights the differences between methods that modify the original array and those that create new arrays.

Uploaded by

hipratikshaa13
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Array Methods Summary

The document provides a comprehensive overview of JavaScript array methods, including basic methods such as length, toString(), at(), join(), pop(), and push(). It also covers more advanced methods like concat(), copyWithin(), flat(), splice(), toSpliced(), and slice(), along with examples demonstrating their usage. Additionally, it highlights the differences between methods that modify the original array and those that create new arrays.

Uploaded by

hipratikshaa13
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

7/10/24, 12:53 PM Array Methods Summary

JavaScript Array Methods


Basic Array Methods
Array length
Array toString()
Array at()
Array join()
Array pop()
Array push()

See Also:
Search Methods
Sort Methods
Iteration Methods Array shift()
Array unshift()
Array delete()
Array concat()
Array copyWithin()
Array flat()
Array splice()
Array toSpliced()
Array slice()
JavaScript Array length
The length property returns the length (size) of an array:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let size = fruits.length;
JavaScript Array toString()
https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 1/74
7/10/24, 12:53 PM Array Methods Summary

The JavaScript method toString() converts an array to a string of


(comma separated) array values.

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
Result:

Banana,Orange,Apple,Mango
JavaScript Array at()
ES2022 intoduced the array method at():

Examples
Get the third element of fruits using at():

const fruits = ["Banana", "Orange", "Apple", "Mango"];


let fruit = fruits.at(2);
Get the third element of fruits using []:

const fruits = ["Banana", "Orange", "Apple", "Mango"];


let fruit = fruits[2];
The at() method returns an indexed element from an array.

The at() method returns the same as [].

The at() method is supported in all modern browsers since March


2022:

Chrome 92 Edge 92 Firefox 90 Safari 15.4 Opera 78

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 2/74
7/10/24, 12:53 PM Array Methods Summary

Apr 2021 Jul 2021 Jul 2021 Mar 2022 Aug 2021
Note
Many languages allows negative bracket indexing like [-1] to access
elements from the end of an object / array / string.

This is not possible in JavaScript, because [] is used for accessing both


arrays and objects. obj[-1] refers to the value of key -1, not to the last
property of the object.

The at() method was introduced in ES2022 to solve this problem.

JavaScript Array join()


The join() method also joins all array elements into a string.

It behaves just like toString(), but in addition you can specify the
separator:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");
Result:

Banana * Orange * Apple * Mango


Popping and Pushing
When you work with arrays, it is easy to remove elements and add
new elements.

This is what popping and pushing is:

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 3/74
7/10/24, 12:53 PM Array Methods Summary

Popping items out of an array, or pushing items into an array.

ADVERTISEMENT

JavaScript Array pop()


The pop() method removes the last element from an array:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop();
The pop() method returns the value that was "popped out":

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits.pop();
JavaScript Array push()
The push() method adds a new element to an array (at the end):

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
The push() method returns the new array length:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let length = fruits.push("Kiwi");
Shifting Elements
Shifting is equivalent to popping, but working on the first element
instead of the last.

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 4/74
7/10/24, 12:53 PM Array Methods Summary

JavaScript Array shift()


The shift() method removes the first array element and "shifts" all
other elements to a lower index.

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift();
The shift() method returns the value that was "shifted out":

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits.shift();
JavaScript Array unshift()
The unshift() method adds a new element to an array (at the
beginning), and "unshifts" older elements:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");
The unshift() method returns the new array length:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");
Changing Elements
Array elements are accessed using their index number:

Array indexes start with 0:

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 5/74
7/10/24, 12:53 PM Array Methods Summary

[0] is the first array element


[1] is the second
[2] is the third ...

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[0] = "Kiwi";
JavaScript Array length
The length property provides an easy way to append a new element
to an array:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Kiwi";
JavaScript Array delete()
Warning !
Using delete() leaves undefined holes in the array.

Use pop() or shift() instead.

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0];
Merging Arrays (Concatenating)
In programming languages, concatenation means joining strings end-
to-end.

Concatenation "snow" and "ball" gives "snowball".

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 6/74
7/10/24, 12:53 PM Array Methods Summary

Concatenating arrays means joining arrays end-to-end.

JavaScript Array concat()


The concat() method creates a new array by merging (concatenating)
existing arrays:

Example (Merging Two Arrays)


const myGirls = ["Cecilie", "Lone"];
const myBoys = ["Emil", "Tobias", "Linus"];

const myChildren = myGirls.concat(myBoys);


Note
The concat() method does not change the existing arrays. It always
returns a new array.

The concat() method can take any number of array arguments.

Example (Merging Three Arrays)


const arr1 = ["Cecilie", "Lone"];
const arr2 = ["Emil", "Tobias", "Linus"];
const arr3 = ["Robin", "Morgan"];
const myChildren = arr1.concat(arr2, arr3);
The concat() method can also take strings as arguments:

Example (Merging an Array with Values)


const arr1 = ["Emil", "Tobias", "Linus"];
const myChildren = arr1.concat("Peter");
Array copyWithin()

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 7/74
7/10/24, 12:53 PM Array Methods Summary

The copyWithin() method copies array elements to another position in


an array:

Examples
Copy to index 2, all elements from index 0:

const fruits = ["Banana", "Orange", "Apple", "Mango"];


fruits.copyWithin(2, 0);
Copy to index 2, the elements from index 0 to 2:

const fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi"];


fruits.copyWithin(2, 0, 2);
Note
The copyWithin() method overwrites the existing values.

The copyWithin() method does not add items to the array.

The copyWithin() method does not change the length of the array.

Flattening an Array
Flattening an array is the process of reducing the dimensionality of an
array.

Flattening is useful when you want to convert a multi-dimensional


array into a one-dimensional array.

JavaScript Array flat()


ES2019 Introduced the Array flat() method.

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 8/74
7/10/24, 12:53 PM Array Methods Summary

The flat() method creates a new array with sub-array elements


concatenated to a specified depth.

Example
const myArr = [[1,2],[3,4],[5,6]];
const newArr = myArr.flat();
Browser Support
JavaScript Array flat() is supported in all modern browsers since
January 2020:

Chrome 69 Edge 79 Firefox 62 Safari 12 Opera 56


Sep 2018 Jan 2020 Sep 2018 Sep 2018 Sep 2018
Splicing and Slicing Arrays
The splice() method adds new items to an array.

The slice() method slices out a piece of an array.

JavaScript Array splice()


The splice() method can be used to add new items to an array:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
The first parameter (2) defines the position where new elements
should be added (spliced in).

The second parameter (0) defines how many elements should be


removed.

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 9/74
7/10/24, 12:53 PM Array Methods Summary

The rest of the parameters ("Lemon" , "Kiwi") define the new elements
to be added.

The splice() method returns an array with the deleted items:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 2, "Lemon", "Kiwi");
Using splice() to Remove Elements
With clever parameter setting, you can use splice() to remove
elements without leaving "holes" in the array:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0, 1);
The first parameter (0) defines the position where new elements
should be added (spliced in).

The second parameter (1) defines how many elements should be


removed.

The rest of the parameters are omitted. No new elements will be


added.

JavaScript Array toSpliced()


ES2023 added the Array toSpliced() method as a safe way to splice an
array without altering the original array.

The difference between the new toSpliced() method and the old

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 10/74
7/10/24, 12:53 PM Array Methods Summary

splice() method is that the new method creates a new array, keeping
the original array unchanged, while the old method altered the
original array.

Example
const months = ["Jan", "Feb", "Mar", "Apr"];
const spliced = months.toSpliced(0, 1);
JavaScript Array slice()
The slice() method slices out a piece of an array into a new array:

Example
Slice out a part of an array starting from array element 1 ("Orange"):

const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];


const citrus = fruits.slice(1);
Note
The slice() method creates a new array.

The slice() method does not remove any elements from the source
array.

Example
Slice out a part of an array starting from array element 3 ("Apple"):

const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];


const citrus = fruits.slice(3);
The slice() method can take two arguments like slice(1, 3).

The method then selects elements from the start argument, and up to

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 11/74
7/10/24, 12:53 PM Array Methods Summary

(but not including) the end argument.

Example
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(1, 3);
If the end argument is omitted, like in the first examples, the slice()
method slices out the rest of the array.

Example
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(2);
Automatic toString()
JavaScript automatically converts an array to a comma separated
string when a primitive value is expected.

This is always the case when you try to output an array.

These two examples will produce the same result:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;
Note
All JavaScript objects have a toString() method.

Searching Arrays

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 12/74
7/10/24, 12:53 PM Array Methods Summary

Searching arrays are covered in the next chapter of this tutorial.

Sorting Arrays
Sorting arrays covers the methods used to sort arraysg.

Iterating Arrays
Iterating arrays covers methods that operate on all array elements.

make short notes including all the code provided of the topics

Sure, here are concise notes including all the provided code examples for the mentioned JavaScript
array methods:

Basic Array Methods

Array length

length property returns the size of an array.

Array toString()

toString() converts an array to a comma-separated string.

javascript Copy code

const fruits = ["Banana", "Orange", "Apple", "Mango"];


document.getElementById("demo").innerHTML = fruits.toString();

Array at() (ES2022)

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 13/74
7/10/24, 12:53 PM Array Methods Summary

at() method returns the element at a specific index.

javascript Copy code

const fruits = ["Banana", "Orange", "Apple", "Mango"]; let fruit = fruits.at(2); //


"Apple"

Array join()

join() joins all elements into a string with a specified separator.

javascript Copy code

const fruits = ["Banana", "Orange", "Apple", "Mango"];


document.getElementById("demo").innerHTML = fruits.join(" * "); // "Banana * Orange *
Apple * Mango"

Popping and Pushing

Array pop()

pop() removes and returns the last element.

javascript Copy code

const fruits = ["Banana", "Orange", "Apple", "Mango"]; let fruit = fruits.pop(); //


"Mango"

Array push()

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 14/74
7/10/24, 12:53 PM Array Methods Summary

push() adds elements to the end of an array and returns the new length.

javascript Copy code

const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.push("Kiwi"); //


["Banana", "Orange", "Apple", "Mango", "Kiwi"]

Shifting Elements

Array shift()

shift() removes and returns the first element, shifting other elements down.

javascript Copy code

const fruits = ["Banana", "Orange", "Apple", "Mango"]; let fruit = fruits.shift(); //


"Banana"

Array unshift()

unshift() adds elements to the beginning of an array and returns the new length.

javascript Copy code

const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.unshift("Lemon"); //


["Lemon", "Banana", "Orange", "Apple", "Mango"]

Changing Elements

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 15/74
7/10/24, 12:53 PM Array Methods Summary

Changing Array Elements

Modify array elements using index.

javascript Copy code

const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits[0] = "Kiwi"; // ["Kiwi",


"Orange", "Apple", "Mango"]

Array length for appending

Use length to append elements.

javascript Copy code

const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits[fruits.length] = "Kiwi";


// ["Banana", "Orange", "Apple", "Mango", "Kiwi"]

Array delete() (avoid)

delete() leaves undefined holes in arrays.

javascript Copy code

const fruits = ["Banana", "Orange", "Apple", "Mango"]; delete fruits[0]; //


["undefined", "Orange", "Apple", "Mango"]

Merging Arrays (Concatenating)

Array concat()
https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 16/74
7/10/24, 12:53 PM Array Methods Summary

concat() merges arrays into a new array.

javascript Copy code

const myGirls = ["Cecilie", "Lone"]; const myBoys = ["Emil", "Tobias", "Linus"]; const
myChildren = myGirls.concat(myBoys); // ["Cecilie", "Lone", "Emil", "Tobias", "Linus"]

Splicing and Slicing Arrays

Array splice()

splice() adds/removes items from an array.

javascript Copy code

const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.splice(2, 0, "Lemon",


"Kiwi"); // ["Banana", "Orange", "Lemon", "Kiwi", "Apple", "Mango"]

Array slice()

slice() extracts a section of an array into a new array.

javascript Copy code

const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; const citrus =


fruits.slice(1, 3); // ["Orange", "Lemon"]

Automatic toString()

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 17/74
7/10/24, 12:53 PM Array Methods Summary

Arrays are automatically converted to comma-separated strings.

javascript Copy code

const fruits = ["Banana", "Orange", "Apple", "Mango"];


document.getElementById("demo").innerHTML = fruits; // "Banana,Orange,Apple,Mango"

These notes cover the basic methods for manipulating arrays in JavaScript. Each method serves a
specific purpose, from accessing elements to modifying the array structure.

JavaScript Array Search


Array Find and Search Methods
Array indexOf()
Array lastIndexOf()
Array includes()

See Also:
Basic Methods
Sort Methods
Iteration Methods Array find()
Array findIndex()
Array findLast()
Array findLastIndex()
JavaScript Array indexOf()
The indexOf() method searches an array for an element value and
returns its position.

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 18/74
7/10/24, 12:53 PM Array Methods Summary

Note: The first item has position 0, the second item has position 1, and
so on.

Example
Search an array for the item "Apple":

const fruits = ["Apple", "Orange", "Apple", "Mango"];


let position = fruits.indexOf("Apple") + 1;
Syntax
array.indexOf(item, start)
item Required. The item to search for.
start Optional. Where to start the search. Negative values will start at
the given position counting from the end, and search to the end.
Array.indexOf() returns -1 if the item is not found.

If the item is present more than once, it returns the position of the
first occurrence.

JavaScript Array lastIndexOf()


Array.lastIndexOf() is the same as Array.indexOf(), but returns the
position of the last occurrence of the specified element.

Example
Search an array for the item "Apple":

const fruits = ["Apple", "Orange", "Apple", "Mango"];


let position = fruits.lastIndexOf("Apple") + 1;
Syntax

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 19/74
7/10/24, 12:53 PM Array Methods Summary

array.lastIndexOf(item, start)
item Required. The item to search for
start Optional. Where to start the search. Negative values will start at
the given position counting from the end, and search to the beginning
JavaScript Array includes()
ECMAScript 2016 introduced Array.includes() to arrays. This allows us
to check if an element is present in an array (including NaN, unlike
indexOf).

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.includes("Mango"); // is true
Syntax
array.includes(search-item)
Array.includes() allows to check for NaN values. Unlike Array.indexOf().

Browser Support
includes() is an ECMAScript 2016 feature.

ES 2016 is fully supported in all modern browsers since March 2017:

Chrome 52 Edge 15 Firefox 52 Safari 10.1 Opera 39


Jul 2016 Apr 2017 Mar 2017 May 2017 Aug 2016
includes() is not supported in Internet Explorer.

ADVERTISEMENT

JavaScript Array find()

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 20/74
7/10/24, 12:53 PM Array Methods Summary

The find() method returns the value of the first array element that
passes a test function.

This example finds (returns the value of) the first element that is larger
than 18:

Example
const numbers = [4, 9, 16, 25, 29];
let first = numbers.find(myFunction);

function myFunction(value, index, array) {


return value > 18;
}
Note that the function takes 3 arguments:

The item value


The item index
The array itself
Browser Support
find() is an ES6 feature (JavaScript 2015).

ES6 is fully supported in all modern browsers since June 2017:

Chrome 51 Edge 15 Firefox 54 Safari 10 Opera 38


May 2016 Apr 2017 Jun 2017 Sep 2016 Jun 2016
find() is not supported in Internet Explorer.

JavaScript Array findIndex()


The findIndex() method returns the index of the first array element

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 21/74
7/10/24, 12:53 PM Array Methods Summary

that passes a test function.

This example finds the index of the first element that is larger than 18:

Example
const numbers = [4, 9, 16, 25, 29];
let first = numbers.findIndex(myFunction);

function myFunction(value, index, array) {


return value > 18;
}
Note that the function takes 3 arguments:

The item value


The item index
The array itself
Browser Support
findIndex() is an ES6 feature (JavaScript 2015).

ES6 is fully supported in all modern browsers since June 2017:

Chrome 51 Edge 15 Firefox 54 Safari 10 Opera 38


May 2016 Apr 2017 Jun 2017 Sep 2016 Jun 2016
findIndex() is not supported in Internet Explorer.

JavaScript Array findLast() Method


ES2023 added the findLast() method that will start from the end of an
array and return the value of the first element that satisfies a
condition.

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 22/74
7/10/24, 12:53 PM Array Methods Summary

Example
const temp = [27, 28, 30, 40, 42, 35, 30];
let high = temp.findLast(x => x > 40);
Browser Support
findLast() is an ES2023 feature.

It is supported in all modern browsers since July 2023:

Chrome 110 Edge 110 Firefox 115 Safari 16.4 Opera 96


Feb 2023 Feb 2023 Jul 2023 Mar 2023 May 2023
JavaScript Array findLastIndex() Method
The findLastIndex() method finds the index of the last element that
satisfies a condition.

Example
const temp = [27, 28, 30, 40, 42, 35, 30];
let pos = temp.findLastIndex(x => x > 40);

do the same for this

Sure, here are concise notes including all the provided code examples for the mentioned JavaScript
array search methods:

Array Find and Search Methods

Array indexOf()

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 23/74
7/10/24, 12:53 PM Array Methods Summary

indexOf() searches an array for a value and returns its first position, or -1 if not found.

javascript Copy code

const fruits = ["Apple", "Orange", "Apple", "Mango"]; let position =


fruits.indexOf("Apple") + 1; // 1

Syntax: array.indexOf(item, start)

Array lastIndexOf()

lastIndexOf() searches for a value and returns its last position, or -1 if not found.

javascript Copy code

const fruits = ["Apple", "Orange", "Apple", "Mango"]; let position =


fruits.lastIndexOf("Apple") + 1; // 3

Syntax: array.lastIndexOf(item, start)

Array includes() (ES2016)

includes() checks if an element is present in an array.

javascript Copy code

const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.includes("Mango"); //


true

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 24/74
7/10/24, 12:53 PM Array Methods Summary

Syntax: array.includes(search-item)

JavaScript Array find()


find() returns the value of the first element that passes a test function.

javascript Copy code

const numbers = [4, 9, 16, 25, 29]; let first = numbers.find(myFunction); function
myFunction(value, index, array) { return value > 18; }

Browser Support: ES6 feature (JavaScript 2015)

JavaScript Array findIndex()


findIndex() returns the index of the first element that passes a test function.

javascript Copy code

const numbers = [4, 9, 16, 25, 29]; let first = numbers.findIndex(myFunction); function
myFunction(value, index, array) { return value > 18; }

Browser Support: ES6 feature (JavaScript 2015)

JavaScript Array findLast() (ES2023)


findLast() returns the value of the first element that satisfies a condition from the end of the
array.

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 25/74
7/10/24, 12:53 PM Array Methods Summary

javascript Copy code

const temp = [27, 28, 30, 40, 42, 35, 30]; let high = temp.findLast(x => x > 40); // 42

Browser Support: ES2023 feature

JavaScript Array findLastIndex() (ES2023)


findLastIndex() returns the index of the last element that satisfies a condition.

javascript Copy code

const temp = [27, 28, 30, 40, 42, 35, 30]; let pos = temp.findLastIndex(x => x > 40);
// 4

Browser Support: ES2023 feature

These notes cover various methods for searching within arrays in JavaScript. Each method serves a
specific purpose, from checking for the presence of an element to finding elements that meet
specific conditions.

JavaScript Sorting Arrays


Array Sort Methods
Alpabetic Sort
Array sort()
Array reverse()
Array toSorted()
https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 26/74
7/10/24, 12:53 PM Array Methods Summary

Array toReversed()
Sorting Objects

See Also:
Basic Methods
Search Methods
Iteration Methods
Numeric Sort
Numeric Sort
Random Sort
Math.min()
Math.max()
Home made Min()
Home made Max()
Sorting an Array
The sort() method sorts an array alphabetically:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
Reversing an Array
The reverse() method reverses the elements in an array:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.reverse();
By combining sort() and reverse(), you can sort an array in descending
order:

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 27/74
7/10/24, 12:53 PM Array Methods Summary

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
fruits.reverse();
JavaScript Array toSorted() Method
ES2023 added the toSorted() method as a safe way to sort an array
without altering the original array.

The difference between toSorted() and sort() is that the first method
creates a new array, keeping the original array unchanged, while the
last method alters the original array.

Example
const months = ["Jan", "Feb", "Mar", "Apr"];
const sorted = months.toSorted();
JavaScript Array toReversed() Method
ES2023 added the toReversed() method as a safe way to reverse an
array without altering the original array.

The difference between toReversed() and reverse() is that the first


method creates a new array, keeping the original array unchanged,
while the last method alters the original array.

Example
const months = ["Jan", "Feb", "Mar", "Apr"];
const reversed = months.toReversed();
Numeric Sort
By default, the sort() function sorts values as strings.

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 28/74
7/10/24, 12:53 PM Array Methods Summary

This works well for strings ("Apple" comes before "Banana").

If numbers are sorted as strings, "25" is bigger than "100", because "2"
is bigger than "1".

Because of this, the sort() method will produce incorrect result when
sorting numbers.

You can fix this by providing a compare function:

Example
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});
Use the same trick to sort an array descending:

Example
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});
ADVERTISEMENT
The Compare Function
The purpose of the compare function is to define an alternative sort
order.

The compare function should return a negative, zero, or positive value,


depending on the arguments:

function(a, b){return a - b}
When the sort() function compares two values, it sends the values to
the compare function, and sorts the values according to the returned

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 29/74
7/10/24, 12:53 PM Array Methods Summary

(negative, zero, positive) value.

If the result is negative, a is sorted before b.

If the result is positive, b is sorted before a.

If the result is 0, no changes are done with the sort order of the two
values.

Example:

The compare function compares all the values in the array, two values
at a time (a, b).

When comparing 40 and 100, the sort() method calls the compare
function(40, 100).

The function calculates 40 - 100 (a - b), and since the result is negative
(-60), the sort function will sort 40 as a value lower than 100.

You can use this code snippet to experiment with numerically and
alphabetically sorting:

<button onclick="myFunction1()">Sort Alphabetically</button>


<button onclick="myFunction2()">Sort Numerically</button>

<p id="demo"></p>

<script>

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 30/74
7/10/24, 12:53 PM Array Methods Summary

const points = [40, 100, 1, 5, 25, 10];


document.getElementById("demo").innerHTML = points;

function myFunction1() {
points.sort();
document.getElementById("demo").innerHTML = points;
}

function myFunction2() {
points.sort(function(a, b){return a - b});
document.getElementById("demo").innerHTML = points;
}
</script>
Sorting an Array in Random Order
Using a sort function, like explained above, you can sort an numeric
array in random order

Example
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(){return 0.5 - Math.random()});

The Fisher Yates Method


The points.sort() method in the example above is not accurate. It will
favor some numbers over others.

The most popular correct method, is called the Fisher Yates shuffle,
and was introduced in data science as early as 1938!

In JavaScript the method can be translated to this:

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 31/74
7/10/24, 12:53 PM Array Methods Summary

Example
const points = [40, 100, 1, 5, 25, 10];

for (let i = points.length -1; i > 0; i--) {


let j = Math.floor(Math.random() * (i+1));
let k = points[i];
points[i] = points[j];
points[j] = k;
}

Find the Lowest (or Highest) Array Value


There are no built-in functions for finding the max or min value in an
array.

To find the lowest or highest value you have 3 options:

Sort the array and read the first or last element


Use Math.min() or Math.max()
Write a home made function
Find Min or Max with sort()
After you have sorted an array, you can use the index to obtain the
highest and lowest values.

Sort Ascending:
Example
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});
// now points[0] contains the lowest value

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 32/74
7/10/24, 12:53 PM Array Methods Summary

// and points[points.length-1] contains the highest value


Sort Descending:
Example
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});
// now points[0] contains the highest value
// and points[points.length-1] contains the lowest value
Note
Sorting a whole array is a very inefficient method if you only want to
find the highest (or lowest) value.

Using Math.min() on an Array


You can use Math.min.apply to find the lowest number in an array:

Example
function myArrayMin(arr) {
return Math.min.apply(null, arr);
}

Math.min.apply(null, [1, 2, 3]) is equivalent to Math.min(1, 2, 3).

Using Math.max() on an Array


You can use Math.max.apply to find the highest number in an array:

Example
function myArrayMax(arr) {
return Math.max.apply(null, arr);
}

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 33/74
7/10/24, 12:53 PM Array Methods Summary

Math.max.apply(null, [1, 2, 3]) is equivalent to Math.max(1, 2, 3).

JavaScript Array Minimum Method


There is no built-in function for finding the lowest value in a JavaScript
array.

The fastest code to find the lowest number is to use a home made
method.

This function loops through an array comparing each value with the
lowest value found:

Example (Find Min)


function myArrayMin(arr) {
let len = arr.length;
let min = Infinity;
while (len--) {
if (arr[len] < min) {
min = arr[len];
}
}
return min;
}

JavaScript Array Maximum Method


There is no built-in function for finding the highest value in a
JavaScript array.

The fastest code to find the highest number is to use a home made

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 34/74
7/10/24, 12:53 PM Array Methods Summary

method.

This function loops through an array comparing each value with the
highest value found:

Example (Find Max)


function myArrayMax(arr) {
let len = arr.length;
let max = -Infinity;
while (len--) {
if (arr[len] > max) {
max = arr[len];
}
}
return max;
}

Sorting Object Arrays


JavaScript arrays often contain objects:

Example
const cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}
];
Even if objects have properties of different data types, the sort()
method can be used to sort the array.

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 35/74
7/10/24, 12:53 PM Array Methods Summary

The solution is to write a compare function to compare the property


values:

Example
cars.sort(function(a, b){return a.year - b.year});
Comparing string properties is a little more complex:

Example
cars.sort(function(a, b){
let x = a.type.toLowerCase();
let y = b.type.toLowerCase();
if (x < y) {return -1;}
if (x > y) {return 1;}
return 0;
});
Stable Array sort()
ES2019 revised the Array sort() method.

Before 2019, the specification allowed unstable sorting algorithms


such as QuickSort.

After ES2019, browsers must use a stable sorting algorithm:

When sorting elements on a value, the elements must keep their


relative position to other elements with the same value.

Example
const myArr = [
{name:"X00",price:100 },

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 36/74
7/10/24, 12:53 PM Array Methods Summary

{name:"X01",price:100 },
{name:"X02",price:100 },
{name:"X03",price:100 },
{name:"X04",price:110 },
{name:"X05",price:110 },
{name:"X06",price:110 },
{name:"X07",price:110 }
];
In the example above, when sorting on price, the result is not allowed
to come out with the names in an other relative position like this:

X01 100
X03 100
X00 100
X03 100
X05 110
X04 110
X06 110
X07 110

do same for this

Certainly! Here are concise notes for JavaScript sorting arrays, including code examples for each
mentioned method:

JavaScript Sorting Arrays

Array Sort Methods

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 37/74
7/10/24, 12:53 PM Array Methods Summary

Alphabetic Sort

sort() sorts an array alphabetically.

javascript Copy code

const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.sort(); // ["Apple",


"Banana", "Mango", "Orange"]

Reversing an Array

reverse() reverses the elements in an array.

javascript Copy code

const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.reverse(); // ["Mango",


"Apple", "Orange", "Banana"]

Combining sort() and reverse() to sort in descending order:

javascript Copy code

const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.sort(); fruits.reverse();


// ["Orange", "Mango", "Banana", "Apple"]

JavaScript Array toSorted() Method (ES2023)

toSorted() sorts an array without altering the original array.

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 38/74
7/10/24, 12:53 PM Array Methods Summary

javascript Copy code

const months = ["Jan", "Feb", "Mar", "Apr"]; const sorted = months.toSorted(); //


["Apr", "Feb", "Jan", "Mar"]

JavaScript Array toReversed() Method (ES2023)

toReversed() reverses an array without altering the original array.

javascript Copy code

const months = ["Jan", "Feb", "Mar", "Apr"]; const reversed = months.toReversed(); //


["Apr", "Mar", "Feb", "Jan"]

Numeric Sort
Default sort() function sorts values as strings, producing incorrect results for numbers. Provide
a compare function for numeric sorting.

Ascending Order

javascript Copy code

const points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){ return a - b }); //
[1, 5, 10, 25, 40, 100]

Descending Order

javascript Copy code

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 39/74
7/10/24, 12:53 PM Array Methods Summary

const points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){ return b - a }); //
[100, 40, 25, 10, 5, 1]

Sorting an Array in Random Order

Using a sort function to sort in random order:

javascript Copy code

const points = [40, 100, 1, 5, 25, 10]; points.sort(function(){ return 0.5 -


Math.random() });

Fisher Yates Shuffle (Accurate Random Sort)

javascript Copy code

const points = [40, 100, 1, 5, 25, 10]; for (let i = points.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1)); [points[i], points[j]] = [points[j],
points[i]]; }

Finding Min and Max Values in an Array


Using Math.min() and Math.max()

javascript Copy code

function myArrayMin(arr) { return Math.min.apply(null, arr); // Finds minimum value }


function myArrayMax(arr) { return Math.max.apply(null, arr); // Finds maximum value }

Homemade Methods for Min and Max

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 40/74
7/10/24, 12:53 PM Array Methods Summary

Find Min

javascript Copy code

function myArrayMin(arr) { let min = Infinity; for (let i = 0; i < arr.length; i++) {
if (arr[i] < min) { min = arr[i]; } } return min; }

Find Max

javascript Copy code

function myArrayMax(arr) { let max = -Infinity; for (let i = 0; i < arr.length; i++) {
if (arr[i] > max) { max = arr[i]; } } return max; }

Sorting Object Arrays

Sorting by Numeric Property

javascript Copy code

const cars = [ {type: "Volvo", year: 2016}, {type: "Saab", year: 2001}, {type: "BMW",
year: 2010} ]; cars.sort(function(a, b){ return a.year - b.year }); // Sorts by year

Sorting by String Property

javascript Copy code

const cars = [ {type: "Volvo", year: 2016}, {type: "Saab", year: 2001}, {type: "BMW",
year: 2010} ]; cars.sort(function(a, b){ let x = a.type.toLowerCase(); let y =
b.type.toLowerCase(); if (x < y) { return -1; } if (x > y) { return 1; } return 0; });

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 41/74
7/10/24, 12:53 PM Array Methods Summary

Stable Array Sort (ES2019)


Ensures elements maintain relative position when sorting.

javascript Copy code

const myArr = [ {name: "X00", price: 100}, {name: "X01", price: 100}, {name: "X02",
price: 100}, {name: "X03", price: 100}, {name: "X04", price: 110}, {name: "X05", price:
110}, {name: "X06", price: 110}, {name: "X07", price: 110} ]; // Sort by price,
maintaining relative order for same price myArr.sort(function(a, b){ return a.price -
b.price });

These notes cover various methods for sorting arrays and finding min/max values in JavaScript,
including handling numeric and object arrays.

2/2

avaScript Array Iteration


Array Iteration Methods
Array iteration methods operate on every array item:

Array forEach
Array map()
Array flatMap()
Array filter()
Array reduce()
Array reduceRight()

See Also:
https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 42/74
7/10/24, 12:53 PM Array Methods Summary

Basic Array Methods


Array Search Methods
Array Sort Methods Array every()
Array some()
Array from()
Array keys()
Array entries()
Array with()
Array Spread (...)
JavaScript Array forEach()
The forEach() method calls a function (a callback function) once for
each array element.

Example
const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);

function myFunction(value, index, array) {


txt += value + "<br>";
}
Note that the function takes 3 arguments:

The item value


The item index
The array itself
The example above uses only the value parameter. The example can
be rewritten to:

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 43/74
7/10/24, 12:53 PM Array Methods Summary

Example
const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);

function myFunction(value) {
txt += value + "<br>";
}
JavaScript Array map()
The map() method creates a new array by performing a function on
each array element.

The map() method does not execute the function for array elements
without values.

The map() method does not change the original array.

This example multiplies each array value by 2:

Example
const numbers1 = [45, 4, 9, 16, 25];
const numbers2 = numbers1.map(myFunction);

function myFunction(value, index, array) {


return value * 2;
}
Note that the function takes 3 arguments:

The item value

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 44/74
7/10/24, 12:53 PM Array Methods Summary

The item index


The array itself
When a callback function uses only the value parameter, the index and
array parameters can be omitted:

Example
const numbers1 = [45, 4, 9, 16, 25];
const numbers2 = numbers1.map(myFunction);

function myFunction(value) {
return value * 2;
}
JavaScript Array flatMap()
ES2019 added the Array flatMap() method to JavaScript.

The flatMap() method first maps all elements of an array and then
creates a new array by flattening the array.

Example
const myArr = [1, 2, 3, 4, 5, 6];
const newArr = myArr.flatMap((x) => x * 2);
Browser Support
JavaScript Array flatMap() is supported in all modern browsers since
January 2020:

Chrome 69 Edge 79 Firefox 62 Safari 12 Opera 56


Sep 2018 Jan 2020 Sep 2018 Sep 2018 Sep 2018
ADVERTISEMENT

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 45/74
7/10/24, 12:53 PM Array Methods Summary

JavaScript Array filter()


The filter() method creates a new array with array elements that pass a
test.

This example creates a new array from elements with a value larger
than 18:

Example
const numbers = [45, 4, 9, 16, 25];
const over18 = numbers.filter(myFunction);

function myFunction(value, index, array) {


return value > 18;
}
Note that the function takes 3 arguments:

The item value


The item index
The array itself
In the example above, the callback function does not use the index
and array parameters, so they can be omitted:

Example
const numbers = [45, 4, 9, 16, 25];
const over18 = numbers.filter(myFunction);

function myFunction(value) {
return value > 18;
}

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 46/74
7/10/24, 12:53 PM Array Methods Summary

JavaScript Array reduce()


The reduce() method runs a function on each array element to
produce (reduce it to) a single value.

The reduce() method works from left-to-right in the array. See also
reduceRight().

The reduce() method does not reduce the original array.

This example finds the sum of all numbers in an array:

Example
const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduce(myFunction);

function myFunction(total, value, index, array) {


return total + value;
}
Note that the function takes 4 arguments:

The total (the initial value / previously returned value)


The item value
The item index
The array itself
The example above does not use the index and array parameters. It
can be rewritten to:

Example
const numbers = [45, 4, 9, 16, 25];

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 47/74
7/10/24, 12:53 PM Array Methods Summary

let sum = numbers.reduce(myFunction);

function myFunction(total, value) {


return total + value;
}
The reduce() method can accept an initial value:

Example
const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduce(myFunction, 100);

function myFunction(total, value) {


return total + value;
}
JavaScript Array reduceRight()
The reduceRight() method runs a function on each array element to
produce (reduce it to) a single value.

The reduceRight() works from right-to-left in the array. See also


reduce().

The reduceRight() method does not reduce the original array.

This example finds the sum of all numbers in an array:

Example
const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduceRight(myFunction);

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 48/74
7/10/24, 12:53 PM Array Methods Summary

function myFunction(total, value, index, array) {


return total + value;
}
Note that the function takes 4 arguments:

The total (the initial value / previously returned value)


The item value
The item index
The array itself
The example above does not use the index and array parameters. It
can be rewritten to:

Example
const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduceRight(myFunction);

function myFunction(total, value) {


return total + value;
}
JavaScript Array every()
The every() method checks if all array values pass a test.

This example checks if all array values are larger than 18:

Example
const numbers = [45, 4, 9, 16, 25];
let allOver18 = numbers.every(myFunction);

function myFunction(value, index, array) {

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 49/74
7/10/24, 12:53 PM Array Methods Summary

return value > 18;


}
Note that the function takes 3 arguments:

The item value


The item index
The array itself
When a callback function uses the first parameter only (value), the
other parameters can be omitted:

Example
const numbers = [45, 4, 9, 16, 25];
let allOver18 = numbers.every(myFunction);

function myFunction(value) {
return value > 18;
}
JavaScript Array some()
The some() method checks if some array values pass a test.

This example checks if some array values are larger than 18:

Example
const numbers = [45, 4, 9, 16, 25];
let someOver18 = numbers.some(myFunction);

function myFunction(value, index, array) {


return value > 18;
}

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 50/74
7/10/24, 12:53 PM Array Methods Summary

Note that the function takes 3 arguments:

The item value


The item index
The array itself
JavaScript Array.from()
The Array.from() method returns an Array object from any object with
a length property or any iterable object.

Example
Create an Array from a String:

Array.from("ABCDEFG");
Browser Support
from() is an ES6 feature (JavaScript 2015).

ES6 is fully supported in all modern browsers since June 2017:

Chrome 51 Edge 15 Firefox 54 Safari 10 Opera 38


May 2016 Apr 2017 Jun 2017 Sep 2016 Jun 2016
from() is not supported in Internet Explorer.

JavaScript Array keys()


The Array.keys() method returns an Array Iterator object with the keys
of an array.

Example
Create an Array Iterator object, containing the keys of the array:

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 51/74
7/10/24, 12:53 PM Array Methods Summary

const fruits = ["Banana", "Orange", "Apple", "Mango"];


const keys = fruits.keys();

for (let x of keys) {


text += x + "<br>";
}
Browser Support
keys() is an ES6 feature (JavaScript 2015).

ES6 is fully supported in all modern browsers since June 2017:

Chrome 51 Edge 15 Firefox 54 Safari 10 Opera 38


May 2016 Apr 2017 Jun 2017 Sep 2016 Jun 2016
keys() is not supported in Internet Explorer.

JavaScript Array entries()


Example
Create an Array Iterator, and then iterate over the key/value pairs:

const fruits = ["Banana", "Orange", "Apple", "Mango"];


const f = fruits.entries();

for (let x of f) {
document.getElementById("demo").innerHTML += x;
}
The entries() method returns an Array Iterator object with key/value
pairs:

[0, "Banana"]

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 52/74
7/10/24, 12:53 PM Array Methods Summary

[1, "Orange"]
[2, "Apple"]
[3, "Mango"]

The entries() method does not change the original array.

Browser Support
entries() is an ES6 feature (JavaScript 2015).

ES6 is fully supported in all modern browsers since June 2017:

Chrome 51 Edge 15 Firefox 54 Safari 10 Opera 38


May 2016 Apr 2017 Jun 2017 Sep 2016 Jun 2016
entries() is not supported in Internet Explorer.

JavaScript Array with() Method


ES2023 added the Array with() method as a safe way to update
elements in an array without altering the original array.

Example
const months = ["Januar", "Februar", "Mar", "April"];
const myMonths = months.with(2, "March");
JavaScript Array Spread (...)
The ... operator expands an iterable (like an array) into more elements:

Example
const q1 = ["Jan", "Feb", "Mar"];
const q2 = ["Apr", "May", "Jun"];
const q3 = ["Jul", "Aug", "Sep"];

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 53/74
7/10/24, 12:53 PM Array Methods Summary

const q4 = ["Oct", "Nov", "May"];

const year = [...q1, ...q2, ...q3, ...q4];


Browser Support
... is an ES6 feature (JavaScript 2015).

ES6 is fully supported in all modern browsers since June 2017:

Chrome 51 Edge 15 Firefox 54 Safari 10 Opera 38


May 2016 Apr 2017 Jun 2017 Sep 2016 Jun 2016
... is not supported in Internet Explorer.

do same for this

JavaScript Array Iteration Methods


Array iteration methods operate on every array item:

Array forEach()

Array map()

Array flatMap()

Array filter()

Array reduce()

Array reduceRight()

See Also:

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 54/74
7/10/24, 12:53 PM Array Methods Summary

Basic Array Methods

Array Search Methods

Array Sort Methods

Array every()

Array some()

Array from()

Array keys()

Array entries()

Array with()

Array Spread (...)

JavaScript Array forEach()


The forEach() method calls a function (a callback function) once for each array element.

javascript Copy code

const numbers = [45, 4, 9, 16, 25]; let txt = ""; numbers.forEach(myFunction); function
myFunction(value, index, array) { txt += value + "<br>"; }

Note that the function takes 3 arguments:

The item value

The item index

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 55/74
7/10/24, 12:53 PM Array Methods Summary

The array itself

Example using only the value parameter:

javascript Copy code

const numbers = [45, 4, 9, 16, 25]; let txt = ""; numbers.forEach(myFunction); function
myFunction(value) { txt += value + "<br>"; }

JavaScript Array map()


The map() method creates a new array by performing a function on each array element. It does not
change the original array.

Example:

javascript Copy code

const numbers1 = [45, 4, 9, 16, 25]; const numbers2 = numbers1.map(myFunction);


function myFunction(value, index, array) { return value * 2; }

Example using only the value parameter:

javascript Copy code

const numbers1 = [45, 4, 9, 16, 25]; const numbers2 = numbers1.map(myFunction);


function myFunction(value) { return value * 2; }

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 56/74
7/10/24, 12:53 PM Array Methods Summary

JavaScript Array flatMap()


ES2019 added the flatMap() method, which first maps all elements of an array and then creates a
new array by flattening the array.

Example:

javascript Copy code

const myArr = [1, 2, 3, 4, 5, 6]; const newArr = myArr.flatMap((x) => x * 2);

JavaScript Array filter()


The filter() method creates a new array with elements that pass a test.

Example:

javascript Copy code

const numbers = [45, 4, 9, 16, 25]; const over18 = numbers.filter(myFunction); function


myFunction(value, index, array) { return value > 18; }

Example using only the value parameter:

javascript Copy code

const numbers = [45, 4, 9, 16, 25]; const over18 = numbers.filter(myFunction); function


myFunction(value) { return value > 18; }

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 57/74
7/10/24, 12:53 PM Array Methods Summary

JavaScript Array reduce()


The reduce() method runs a function on each array element to produce a single value.

Example:

javascript Copy code

const numbers = [45, 4, 9, 16, 25]; let sum = numbers.reduce(myFunction); function


myFunction(total, value, index, array) { return total + value; }

Example using only the total and value parameters:

javascript Copy code

const numbers = [45, 4, 9, 16, 25]; let sum = numbers.reduce(myFunction); function


myFunction(total, value) { return total + value; }

The reduce() method can accept an initial value:

javascript Copy code

const numbers = [45, 4, 9, 16, 25]; let sum = numbers.reduce(myFunction, 100); function
myFunction(total, value) { return total + value; }

JavaScript Array reduceRight()

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 58/74
7/10/24, 12:53 PM Array Methods Summary

The reduceRight() method runs a function on each array element to produce a single value, working
from right to left.

Example:

javascript Copy code

const numbers = [45, 4, 9, 16, 25]; let sum = numbers.reduceRight(myFunction); function


myFunction(total, value, index, array) { return total + value; }

Example using only the total and value parameters:

javascript Copy code

const numbers = [45, 4, 9, 16, 25]; let sum = numbers.reduceRight(myFunction); function


myFunction(total, value) { return total + value; }

JavaScript Array every()


The every() method checks if all array values pass a test.

Example:

javascript Copy code

const numbers = [45, 4, 9, 16, 25]; let allOver18 = numbers.every(myFunction); function


myFunction(value, index, array) { return value > 18; }

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 59/74
7/10/24, 12:53 PM Array Methods Summary

Example using only the value parameter:

javascript Copy code

const numbers = [45, 4, 9, 16, 25]; let allOver18 = numbers.every(myFunction); function


myFunction(value) { return value > 18; }

JavaScript Array some()


The some() method checks if some array values pass a test.

Example:

javascript Copy code

const numbers = [45, 4, 9, 16, 25]; let someOver18 = numbers.some(myFunction); function


myFunction(value, index, array) { return value > 18; }

JavaScript Array.from()
The Array.from() method returns an Array object from any object with a length property or any
iterable object.

Example:

javascript Copy code

Array.from("ABCDEFG");

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 60/74
7/10/24, 12:53 PM Array Methods Summary

JavaScript Array keys()


The Array.keys() method returns an Array Iterator object with the keys of an array.

Example:

javascript Copy code

const fruits = ["Banana", "Orange", "Apple", "Mango"]; const keys = fruits.keys(); for
(let x of keys) { text += x + "<br>"; }

JavaScript Array entries()


The entries() method returns an Array Iterator object with key/value pairs.

Example:

javascript Copy code

const fruits = ["Banana", "Orange", "Apple", "Mango"]; const f = fruits.entries(); for


(let x of f) { document.getElementById("demo").innerHTML += x; }

JavaScript Array with() Method


ES2023 added the with() method as a safe way to update elements in an array without altering the
original array.

Example:

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 61/74
7/10/24, 12:53 PM Array Methods Summary

javascript Copy code

const months = ["Januar", "Februar", "Mar", "April"]; const myMonths = months.with(2,


"March");

JavaScript Array Spread (...)


The ... operator expands an iterable (like an array) into more elements.

Example:

javascript Copy code

const q1 = ["Jan", "Feb", "Mar"]; const q2 = ["Apr", "May", "Jun"]; const q3 = ["Jul",
"Aug", "Sep"]; const q4 = ["Oct", "Nov", "May"]; const year = [...q1, ...q2, ...q3,
...q4];

continue the above if not completed

Browser Support
Most of the mentioned methods are ES6 features (JavaScript 2015) and are fully supported in all
modern browsers since June 2017. Here's a summary:

JavaScript Array flatMap()

Chrome 69

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 62/74
7/10/24, 12:53 PM Array Methods Summary

Edge 79

Firefox 62

Safari 12

Opera 56

JavaScript Array.from()

Chrome 51

Edge 15

Firefox 54

Safari 10

Opera 38

JavaScript Array keys()

Chrome 51

Edge 15

Firefox 54

Safari 10

Opera 38

JavaScript Array entries()

Chrome 51

Edge 15

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 63/74
7/10/24, 12:53 PM Array Methods Summary

Firefox 54

Safari 10

Opera 38

JavaScript Array with() Method

ES2023 feature; support may vary based on browser updates.

JavaScript Array Spread (...)

Chrome 51

Edge 15

Firefox 54

Safari 10

Opera 38

Note that some of these methods are not supported in Internet Explorer.

JavaScript Array Const


ECMAScript 2015 (ES6)
In 2015, JavaScript introduced an important new keyword: const.

It has become a common practice to declare arrays using const:

Example
const cars = ["Saab", "Volvo", "BMW"];
Cannot be Reassigned
https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 64/74
7/10/24, 12:53 PM Array Methods Summary

An array declared with const cannot be reassigned:

Example
const cars = ["Saab", "Volvo", "BMW"];
cars = ["Toyota", "Volvo", "Audi"]; // ERROR
Arrays are Not Constants
The keyword const is a little misleading.

It does NOT define a constant array. It defines a constant reference to


an array.

Because of this, we can still change the elements of a constant array.

Elements Can be Reassigned


You can change the elements of a constant array:

Example
// You can create a constant array:
const cars = ["Saab", "Volvo", "BMW"];

// You can change an element:


cars[0] = "Toyota";

// You can add an element:


cars.push("Audi");
Browser Support
The const keyword is not supported in Internet Explorer 10 or earlier.

The following table defines the first browser versions with full support

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 65/74
7/10/24, 12:53 PM Array Methods Summary

for the const keyword:

Chrome 49 IE 11 / Edge Firefox 36 Safari 10 Opera 36


Mar, 2016 Oct, 2013 Feb, 2015 Sep, 2016 Mar, 2016
Assigned when Declared
JavaScript const variables must be assigned a value when they are
declared:

Meaning: An array declared with const must be initialized when it is


declared.

Using const without initializing the array is a syntax error:

Example
This will not work:

const cars;
cars = ["Saab", "Volvo", "BMW"];
Arrays declared with var can be initialized at any time.

You can even use the array before it is declared:

Example
This is OK:

cars = ["Saab", "Volvo", "BMW"];


var cars;
Const Block Scope
An array declared with const has Block Scope.

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 66/74
7/10/24, 12:53 PM Array Methods Summary

An array declared in a block is not the same as an array declared


outside the block:

Example
const cars = ["Saab", "Volvo", "BMW"];
// Here cars[0] is "Saab"
{
const cars = ["Toyota", "Volvo", "BMW"];
// Here cars[0] is "Toyota"
}
// Here cars[0] is "Saab"
An array declared with var does not have block scope:

Example
var cars = ["Saab", "Volvo", "BMW"];
// Here cars[0] is "Saab"
{
var cars = ["Toyota", "Volvo", "BMW"];
// Here cars[0] is "Toyota"
}
// Here cars[0] is "Toyota"
You can learn more about Block Scope in the chapter: JavaScript
Scope.

ADVERTISEMENT

Redeclaring Arrays
Redeclaring an array declared with var is allowed anywhere in a

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 67/74
7/10/24, 12:53 PM Array Methods Summary

program:

Example
var cars = ["Volvo", "BMW"]; // Allowed
var cars = ["Toyota", "BMW"]; // Allowed
cars = ["Volvo", "Saab"]; // Allowed
Redeclaring or reassigning an array to const, in the same scope, or in
the same block, is not allowed:

Example
var cars = ["Volvo", "BMW"]; // Allowed
const cars = ["Volvo", "BMW"]; // Not allowed
{
var cars = ["Volvo", "BMW"]; // Allowed
const cars = ["Volvo", "BMW"]; // Not allowed
}
Redeclaring or reassigning an existing const array, in the same scope,
or in the same block, is not allowed:

Example
const cars = ["Volvo", "BMW"]; // Allowed
const cars = ["Volvo", "BMW"]; // Not allowed
var cars = ["Volvo", "BMW"]; // Not allowed
cars = ["Volvo", "BMW"]; // Not allowed

{
const cars = ["Volvo", "BMW"]; // Allowed
const cars = ["Volvo", "BMW"]; // Not allowed
var cars = ["Volvo", "BMW"]; // Not allowed

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 68/74
7/10/24, 12:53 PM Array Methods Summary

cars = ["Volvo", "BMW"]; // Not allowed


}
Redeclaring an array with const, in another scope, or in another block,
is allowed:

Example
const cars = ["Volvo", "BMW"]; // Allowed
{
const cars = ["Volvo", "BMW"]; // Allowed
}
{
const cars = ["Volvo", "BMW"]; // Allowed
}

do the same for this

JavaScript Array Const

ECMAScript 2015 (ES6)

In 2015, JavaScript introduced an important new keyword: const. It has become a common practice
to declare arrays using const.

Example:

javascript Copy code

const cars = ["Saab", "Volvo", "BMW"];

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 69/74
7/10/24, 12:53 PM Array Methods Summary

Cannot be Reassigned

An array declared with const cannot be reassigned.

Example:

javascript Copy code

const cars = ["Saab", "Volvo", "BMW"]; cars = ["Toyota", "Volvo", "Audi"]; // ERROR

Arrays are Not Constants

The keyword const is a little misleading. It does NOT define a constant array. It defines a constant
reference to an array. Because of this, we can still change the elements of a constant array.

Elements Can be Reassigned

You can change the elements of a constant array.

Example:

javascript Copy code

// You can create a constant array: const cars = ["Saab", "Volvo", "BMW"]; // You can
change an element: cars[0] = "Toyota"; // You can add an element: cars.push("Audi");

Browser Support

The const keyword is not supported in Internet Explorer 10 or earlier. The following table defines the
first browser versions with full support for the const keyword:

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 70/74
7/10/24, 12:53 PM Array Methods Summary

Browser Version Date

Chrome 49 Mar 2016

IE 11 / Edge Oct 2013

Firefox 36 Feb 2015

Safari 10 Sep 2016

Opera 36 Mar 2016

Assigned when Declared

JavaScript const variables must be assigned a value when they are declared. An array declared with
const must be initialized when it is declared. Using const without initializing the array is a syntax

error.

Example:

javascript Copy code

const cars; // This will not work cars = ["Saab", "Volvo", "BMW"];

Arrays declared with var can be initialized at any time. You can even use the array before it is
declared.

Example:

javascript Copy code

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 71/74
7/10/24, 12:53 PM Array Methods Summary

cars = ["Saab", "Volvo", "BMW"]; var cars;

Const Block Scope

An array declared with const has Block Scope. An array declared in a block is not the same as an
array declared outside the block.

Example:

javascript Copy code

const cars = ["Saab", "Volvo", "BMW"]; // Here cars[0] is "Saab" { const cars =
["Toyota", "Volvo", "BMW"]; // Here cars[0] is "Toyota" } // Here cars[0] is "Saab"

An array declared with var does not have block scope.

Example:

javascript Copy code

var cars = ["Saab", "Volvo", "BMW"]; // Here cars[0] is "Saab" { var cars = ["Toyota",
"Volvo", "BMW"]; // Here cars[0] is "Toyota" } // Here cars[0] is "Toyota"

Redeclaring Arrays

Redeclaring an array declared with var is allowed anywhere in a program.

Example:

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 72/74
7/10/24, 12:53 PM Array Methods Summary

javascript Copy code

var cars = ["Volvo", "BMW"]; // Allowed var cars = ["Toyota", "BMW"]; // Allowed cars =
["Volvo", "Saab"]; // Allowed

Redeclaring or reassigning an array to const, in the same scope, or in the same block, is not allowed.

Example:

javascript Copy code

var cars = ["Volvo", "BMW"]; // Allowed const cars = ["Volvo", "BMW"]; // Not allowed {
var cars = ["Volvo", "BMW"]; // Allowed const cars = ["Volvo", "BMW"]; // Not allowed }

Redeclaring or reassigning an existing const array, in the same scope, or in the same block, is not
allowed.

Example:

javascript Copy code

const cars = ["Volvo", "BMW"]; // Allowed const cars = ["Volvo", "BMW"]; // Not allowed
var cars = ["Volvo", "BMW"]; // Not allowed cars = ["Volvo", "BMW"]; // Not allowed {
const cars = ["Volvo", "BMW"]; // Allowed const cars = ["Volvo", "BMW"]; // Not allowed
var cars = ["Volvo", "BMW"]; // Not allowed cars = ["Volvo", "BMW"]; // Not allowed }

Redeclaring an array with const, in another scope, or in another block, is allowed.

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 73/74
7/10/24, 12:53 PM Array Methods Summary

Example:

javascript Copy code

const cars = ["Volvo", "BMW"]; // Allowed { const cars = ["Volvo", "BMW"]; // Allowed }
{ const cars = ["Volvo", "BMW"]; // Allowed }

https://chatgpt.com/c/d16487fb-ae44-42df-ace7-9437ed30768e 74/74

You might also like