Array[@@species] - JavaScript

Array[@@species]
================

The **`Array[@@species]`** static accessor property returns the constructor used to construct return values from array methods.

**Warning:** The existence of `@@species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are investigating whether to remove this feature. Avoid relying on it if possible. Modern array methods, such as `toReversed()`, do not use `@@species` and always return a new `Array` base class instance.

Syntax
------

```js
Array[Symbol.species]
```

### Return value

The value of the constructor (`this`) on which `get @@species` was called. The return value is used to construct return values from array methods that create new arrays.

Description
-----------

The `@@species` accessor property returns the default constructor for `Array` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically:

```js
// Hypothetical underlying implementation for illustration
class Array {
  static get [Symbol.species]() {
    return this;
  }
}
```

Because of this polymorphic implementation, `@@species` of derived subclasses would also return the constructor itself by default.

```js
class SubArray extends Array {}
SubArray[Symbol.species] === SubArray; // true
```

When calling array methods that do not mutate the existing array but return a new array instance (for example, `filter()` and `map()`), the array's `constructor[@@species]` will be accessed. The returned constructor will be used to construct the return value of the array method. This makes it technically possible to make array methods return objects unrelated to arrays.

```js
class NotAnArray {
  constructor(length) {
    this.length = length;
  }
}

const arr = [0, 1, 2];
arr.constructor = { [Symbol.species]: NotAnArray };
arr.map((i) => i); // NotAnArray { '0': 0, '1': 1, '2': 2, length: 3 }
arr.filter((i) => i); // NotAnArray { '0': 1, '1': 2, length: 0 }
arr.concat([1, 2]); // NotAnArray { '0': 0, '1': 1, '2': 2, '3': 1, '4': 2, length: 5 }
```

Examples
--------

### Species in ordinary objects

The `@@species` property returns the default constructor function, which is the `Array` constructor for `Array`.

```js
Array[Symbol.species]; // [Function: Array]
```

### Species in derived objects

In an instance of a custom `Array` subclass, such as `MyArray`, the `MyArray` species is the `MyArray` constructor. However, you might want to overwrite this, in order to return parent `Array` objects in your derived class methods:

```js
class MyArray extends Array {
  // Overwrite MyArray species to the parent Array constructor
  static get [Symbol.species]() {
    return Array;
  }
}
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-get-array-@@species |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Array[@@species]` and support of `@@species` in all affected `Array` methods in `core-js`
* Indexed collections guide
* `Array`
* `Symbol.species`


Array.prototype.sort() - JavaScript

Array.prototype.sort()
======================

The **`sort()`** method of `Array` instances sorts the elements of an array *in place* and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

 The time and space complexity of the sort cannot be guaranteed as it depends on the
 implementation.

To sort the elements in an array without mutating the original array, use `toSorted()`.

Try it
------

Syntax
------

```js
sort()
sort(compareFn)
```

### Parameters

`compareFn` Optional

A function that defines the sort order. The return value should be a number whose sign indicates the relative order of the two elements: negative if `a` is less than `b`, positive if `a` is greater than `b`, and zero if they are equal. `NaN` is treated as `0`. The function is called with the following arguments:

`a`

The first element for comparison. Will never be `undefined`.

`b`

The second element for comparison. Will never be `undefined`.

If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value.

### Return value

The reference to the original array, now sorted. Note that the array is sorted *in place*, and no copy is made.

Description
-----------

 If `compareFn` is not supplied, all non-`undefined` array
 elements are sorted by converting them to strings and comparing strings in UTF-16 code
 units order. For example, "banana" comes before "cherry". In a numeric sort, 9 comes
 before 80, but because numbers are converted to strings, "80" comes before "9" in the
 Unicode order. All `undefined` elements are sorted to the end of the array.

The `sort()` method preserves empty slots. If the source array is sparse, the empty slots are moved to the end of the array, and always come after all the `undefined`.

**Note:** In UTF-16, Unicode characters above `\uFFFF` are
 encoded as two surrogate code units, of the range
 `\uD800` - `\uDFFF`. The value of each code unit is taken
 separately into account for the comparison. Thus the character formed by the surrogate
 pair `\uD855\uDE51` will be sorted before the character
 `\uFF3A`.

 If `compareFn` is supplied, all non-`undefined` array
 elements are sorted according to the return value of the compare function (all
 `undefined` elements are sorted to the end of the array, with no call to
 `compareFn`).

| `compareFn(a, b)` return value | sort order |
| --- | --- |
| > 0 | sort `a` after `b`, e.g. `[b, a]` |
| < 0 | sort `a` before `b`, e.g. `[a, b]` |
| === 0 | keep original order of `a` and `b` |

So, the compare function has the following form:

```js
function compareFn(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  } else if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
```

More formally, the comparator is expected to have the following properties, in order to ensure proper sort behavior:

* *Pure*: The comparator does not mutate the objects being compared or any external state. (This is important because there's no guarantee *when* and *how* the comparator will be called, so any particular call should not produce visible effects to the outside.)
* *Stable*: The comparator returns the same result with the same pair of input.
* *Reflexive*: `compareFn(a, a) === 0`.
* *Anti-symmetric*: `compareFn(a, b)` and `compareFn(b, a)` must both be `0` or have opposite signs.
* *Transitive*: If `compareFn(a, b)` and `compareFn(b, c)` are both positive, zero, or negative, then `compareFn(a, c)` has the same positivity as the previous two.

A comparator conforming to the constraints above will always be able to return all of `1`, `0`, and `-1`, or consistently return `0`. For example, if a comparator only returns `1` and `0`, or only returns `0` and `-1`, it will not be able to sort reliably because *anti-symmetry* is broken. A comparator that always returns `0` will cause the array to not be changed at all, but is reliable nonetheless.

The default lexicographic comparator satisfies all constraints above.

 To compare numbers instead of strings, the compare function can subtract `b`
 from `a`. The following function will sort the array in ascending order (if
 it doesn't contain `NaN`):

```js
function compareNumbers(a, b) {
  return a - b;
}
```

The `sort()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.

Examples
--------

### Creating, displaying, and sorting an array

 The following example creates four arrays and displays the original array, then the
 sorted arrays. The numeric arrays are sorted without a compare function, then sorted
 using one.

```js
const stringArray = ["Blue", "Humpback", "Beluga"];
const numberArray = [40, 1, 5, 200];
const numericStringArray = ["80", "9", "700"];
const mixedNumericArray = ["80", "9", "700", 40, 1, 5, 200];

function compareNumbers(a, b) {
  return a - b;
}

stringArray.join(); // 'Blue,Humpback,Beluga'
stringArray.sort(); // ['Beluga', 'Blue', 'Humpback']

numberArray.join(); // '40,1,5,200'
numberArray.sort(); // [1, 200, 40, 5]
numberArray.sort(compareNumbers); // [1, 5, 40, 200]

numericStringArray.join(); // '80,9,700'
numericStringArray.sort(); // ['700', '80', '9']
numericStringArray.sort(compareNumbers); // ['9', '80', '700']

mixedNumericArray.join(); // '80,9,700,40,1,5,200'
mixedNumericArray.sort(); // [1, 200, 40, 5, '700', '80', '9']
mixedNumericArray.sort(compareNumbers); // [1, 5, '9', 40, '80', 200, '700']
```

### Sorting array of objects

Arrays of objects can be sorted by comparing the value of one of their properties.

```js
const items = [
  { name: "Edward", value: 21 },
  { name: "Sharpe", value: 37 },
  { name: "And", value: 45 },
  { name: "The", value: -12 },
  { name: "Magnetic", value: 13 },
  { name: "Zeros", value: 37 },
];

// sort by value
items.sort((a, b) => a.value - b.value);

// sort by name
items.sort((a, b) => {
  const nameA = a.name.toUpperCase(); // ignore upper and lowercase
  const nameB = b.name.toUpperCase(); // ignore upper and lowercase
  if (nameA < nameB) {
    return -1;
  }
  if (nameA > nameB) {
    return 1;
  }

  // names must be equal
  return 0;
});
```

### Sorting non-ASCII characters

 For sorting strings with non-ASCII characters, i.e. strings with accented characters
 (e, é, è, a, ä, etc.), strings from languages other than English, use
 `String.prototype.localeCompare()`. This function can compare those characters so they
 appear in the right order.

```js
const items = ["réservé", "premier", "communiqué", "café", "adieu", "éclair"];
items.sort((a, b) => a.localeCompare(b));

// items is ['adieu', 'café', 'communiqué', 'éclair', 'premier', 'réservé']
```

### Sorting with map

 The `compareFn` can be invoked multiple times per element within the
 array. Depending on the `compareFn`'s nature, this may yield a high
 overhead. The more work a `compareFn` does and the more elements there
 are to sort, it may be more efficient to use `map()` for
 sorting. The idea is to traverse the array once to extract the actual values used for
 sorting into a temporary array, sort the temporary array, and then traverse the
 temporary array to achieve the right order.

```js
// the array to be sorted
const data = ["delta", "alpha", "charlie", "bravo"];

// temporary array holds objects with position and sort-value
const mapped = data.map((v, i) => {
  return { i, value: someSlowOperation(v) };
});

// sorting the mapped array containing the reduced values
mapped.sort((a, b) => {
  if (a.value > b.value) {
    return 1;
  }
  if (a.value < b.value) {
    return -1;
  }
  return 0;
});

const result = mapped.map((v) => data[v.i]);
```

There is an open source library available called mapsort which applies this approach.

### sort() returns the reference to the same array

The `sort()` method returns a reference to the original array, so mutating the returned array will mutate the original array as well.

```js
const numbers = [3, 1, 4, 1, 5];
const sorted = numbers.sort((a, b) => a - b);
// numbers and sorted are both [1, 1, 3, 4, 5]
sorted[0] = 10;
console.log(numbers[0]); // 10
```

In case you want `sort()` to not mutate the original array, but return a shallow-copied array like other array methods (e.g. `map()`) do, use the `toSorted()` method. Alternatively, you can do a shallow copy before calling `sort()`, using the spread syntax or `Array.from()`.

```js
const numbers = [3, 1, 4, 1, 5];
// [...numbers] creates a shallow copy, so sort() does not mutate the original
const sorted = [...numbers].sort((a, b) => a - b);
sorted[0] = 10;
console.log(numbers[0]); // 3
```

### Sort stability

Since version 10 (or ECMAScript 2019), the specification dictates that `Array.prototype.sort` is stable.

For example, say you had a list of students alongside their grades. Note that the list of students is already pre-sorted by name in alphabetical order:

```js
const students = [
  { name: "Alex", grade: 15 },
  { name: "Devlin", grade: 15 },
  { name: "Eagle", grade: 13 },
  { name: "Sam", grade: 14 },
];
```

After sorting this array by `grade` in ascending order:

```js
students.sort((firstItem, secondItem) => firstItem.grade - secondItem.grade);
```

The `students` variable will then have the following value:

```js
[
  { name: "Eagle", grade: 13 },
  { name: "Sam", grade: 14 },
  { name: "Alex", grade: 15 }, // original maintained for similar grade (stable sorting)
  { name: "Devlin", grade: 15 }, // original maintained for similar grade (stable sorting)
];
```

It's important to note that students that have the same grade (for example, Alex and Devlin), will remain in the same order as before calling the sort. This is what a stable sorting algorithm guarantees.

Before version 10 (or ECMAScript 2019), sort stability was not guaranteed, meaning that you could end up with the following:

```js
[
  { name: "Eagle", grade: 13 },
  { name: "Sam", grade: 14 },
  { name: "Devlin", grade: 15 }, // original order not maintained
  { name: "Alex", grade: 15 }, // original order not maintained
];
```

### Sorting with non-well-formed comparator

If a comparing function does not satisfy all of purity, stability, reflexivity, anti-symmetry, and transitivity rules, as explained in the description, the program's behavior is not well-defined.

For example, consider this code:

```js
const arr = [3, 1, 4, 1, 5, 9];
const compareFn = (a, b) => (a > b ? 1 : 0);
arr.sort(compareFn);
```

The `compareFn` function here is not well-formed, because it does not satisfy anti-symmetry: if `a > b`, it returns `1`; but by swapping `a` and `b`, it returns `0` instead of a negative value. Therefore, the resulting array will be different across engines. For example, V8 (used by Chrome, Node.js, etc.) and JavaScriptCore (used by Safari) would not sort the array at all and return `[3, 1, 4, 1, 5, 9]`, while SpiderMonkey (used by Firefox) will return the array sorted ascendingly, as `[1, 1, 3, 4, 5, 9]`.

However, if the `compareFn` function is changed slightly so that it returns `-1` or `0`:

```js
const arr = [3, 1, 4, 1, 5, 9];
const compareFn = (a, b) => (a > b ? -1 : 0);
arr.sort(compareFn);
```

Then V8 and JavaScriptCore sorts it descendingly, as `[9, 5, 4, 3, 1, 1]`, while SpiderMonkey returns it as-is: `[3, 1, 4, 1, 5, 9]`.

Due to this implementation inconsistency, you are always advised to make your comparator well-formed by following the five constraints.

### Using sort() on sparse arrays

Empty slots are moved to the end of the array.

```js
console.log(["a", "c", , "b"].sort()); // ['a', 'b', 'c', empty]
console.log([, undefined, "a", "b"].sort()); // ["a", "b", undefined, empty]
```

### Calling sort() on non-array objects

The `sort()` method reads the `length` property of `this`. It then collects all existing integer-keyed properties in the range of `0` to `length - 1`, sorts them, and writes them back. If there are missing properties in the range, the corresponding trailing properties are deleted, as if the non-existent properties are sorted towards the end.

```js
const arrayLike = {
  length: 3,
  unrelated: "foo",
  0: 5,
  2: 4,
};
console.log(Array.prototype.sort.call(arrayLike));
// { '0': 4, '1': 5, length: 3, unrelated: 'foo' }
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.sort |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Array.prototype.sort` with modern behavior like stable sort in `core-js`
* Indexed collections guide
* `Array`
* `Array.prototype.reverse()`
* `Array.prototype.toSorted()`
* `String.prototype.localeCompare()`
* `TypedArray.prototype.sort()`
* Getting things sorted in V8 on v8.dev (2018)
* Stable `Array.prototype.sort` on v8.dev (2019)
* `Array.prototype.sort` stability by Mathias Bynens


Array.prototype.every() - JavaScript

Array.prototype.every()
=======================

 The **`every()`** method of `Array` instances tests whether
 all elements in the array pass the test implemented by the provided function. It
 returns a Boolean value.

Try it
------

Syntax
------

```js
every(callbackFn)
every(callbackFn, thisArg)
```

### Parameters

`callbackFn`

A function to execute for each element in the array. It should return a truthy value to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments:

`element`

The current element being processed in the array.

`index`

The index of the current element being processed in the array.

`array`

The array `every()` was called upon.

`thisArg` Optional

A value to use as `this` when executing `callbackFn`. See iterative methods.

### Return value

`true` unless `callbackFn` returns a falsy value for an array element, in which case `false` is immediately returned.

Description
-----------

The `every()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, until the `callbackFn` returns a falsy value. If such an element is found, `every()` immediately returns `false` and stops iterating through the array. Otherwise, if `callbackFn` returns a truthy value for all elements, `every()` returns `true`. Read the iterative methods section for more information about how these methods work in general.

`every` acts like the "for all" quantifier in mathematics. In particular, for an empty array, it returns `true`. (It is vacuously true that all elements of the empty set satisfy any given condition.)

`callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays.

The `every()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties.

Examples
--------

### Testing size of all array elements

The following example tests whether all elements in the array are 10 or bigger.

```js
function isBigEnough(element, index, array) {
  return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough); // false
[12, 54, 18, 130, 44].every(isBigEnough); // true
```

### Check if one array is a subset of another array

The following example tests if all the elements of an array are present in another array.

```js
const isSubset = (array1, array2) =>
  array2.every((element) => array1.includes(element));

console.log(isSubset([1, 2, 3, 4, 5, 6, 7], [5, 7, 6])); // true
console.log(isSubset([1, 2, 3, 4, 5, 6, 7], [5, 8, 7])); // false
```

### Using the third argument of callbackFn

The `array` argument is useful if you want to access another element in the array. The following example first uses `filter()` to extract the positive values and then uses `every()` to check whether the array is strictly increasing.

```js
const numbers = [-2, 4, -8, 16, -32];
const isIncreasing = numbers
  .filter((num) => num > 0)
  .every((num, idx, arr) => {
    // Without the arr argument, there's no way to easily access the
    // intermediate array without saving it to a variable.
    if (idx === 0) return true;
    return num > arr[idx - 1];
  });
console.log(isIncreasing); // true
```

### Using every() on sparse arrays

`every()` will not run its predicate on empty slots.

```js
console.log([1, , 3].every((x) => x !== undefined)); // true
console.log([2, , 2].every((x) => x === 2)); // true
```

### Calling every() on non-array objects

The `every()` method reads the `length` property of `this` and then accesses each property with a nonnegative integer key less than `length` until they all have been accessed or `callbackFn` returns `false`.

```js
const arrayLike = {
  length: 3,
  0: "a",
  1: "b",
  2: "c",
  3: 345, // ignored by every() since length is 3
};
console.log(
  Array.prototype.every.call(arrayLike, (x) => typeof x === "string"),
); // true
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.every |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Array.prototype.every` in `core-js`
* Indexed collections guide
* `Array`
* `Array.prototype.forEach()`
* `Array.prototype.some()`
* `Array.prototype.find()`
* `TypedArray.prototype.every()`


Array.prototype.includes() - JavaScript

Array.prototype.includes()
==========================

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

Try it
------

Syntax
------

```js
includes(searchElement)
includes(searchElement, fromIndex)
```

### Parameters

`searchElement`

The value to search for.

`fromIndex` Optional

Zero-based index at which to start searching, converted to an integer.

* Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. However, the array is still searched from front to back in this case.
* If `fromIndex < -array.length` or `fromIndex` is omitted, `0` is used, causing the entire array to be searched.
* If `fromIndex >= array.length`, the array is not searched and `false` is returned.

### Return value

A boolean value which is `true` if the value `searchElement` is found within the array (or the part of the array indicated by the index `fromIndex`, if specified).

Description
-----------

The `includes()` method compares `searchElement` to elements of the array using the SameValueZero algorithm. Values of zero are all considered to be equal, regardless of sign. (That is, `-0` is equal to `0`), but `false` is *not* considered to be the same as `0`. `NaN` can be correctly searched for.

When used on sparse arrays, the `includes()` method iterates empty slots as if they have the value `undefined`.

The `includes()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties.

Examples
--------

### Using includes()

```js
[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false
[1, 2, 3].includes(3, 3); // false
[1, 2, 3].includes(3, -1); // true
[1, 2, NaN].includes(NaN); // true
["1", "2", "3"].includes(3); // false
```

### fromIndex is greater than or equal to the array length

 If `fromIndex` is greater than or equal to the length of the
 array, `false` is returned. The array will not be searched.

```js
const arr = ["a", "b", "c"];

arr.includes("c", 3); // false
arr.includes("c", 100); // false
```

### Computed index is less than 0

 If `fromIndex` is negative, the computed index is calculated to
 be used as a position in the array at which to begin searching for
 `searchElement`. If the computed index is less than or equal to
 `0`, the entire array will be searched.

```js
// array length is 3
// fromIndex is -100
// computed index is 3 + (-100) = -97

const arr = ["a", "b", "c"];

arr.includes("a", -100); // true
arr.includes("b", -100); // true
arr.includes("c", -100); // true
arr.includes("a", -2); // false
```

### Using includes() on sparse arrays

You can search for `undefined` in a sparse array and get `true`.

```js
console.log([1, , 3].includes(undefined)); // true
```

### Calling includes() on non-array objects

The `includes()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`.

```js
const arrayLike = {
  length: 3,
  0: 2,
  1: 3,
  2: 4,
  3: 1, // ignored by includes() since length is 3
};
console.log(Array.prototype.includes.call(arrayLike, 2));
// true
console.log(Array.prototype.includes.call(arrayLike, 1));
// false
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.includes |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Array.prototype.includes` in `core-js`
* Indexed collections guide
* `Array`
* `Array.prototype.indexOf()`
* `Array.prototype.find()`
* `Array.prototype.findIndex()`
* `TypedArray.prototype.includes()`
* `String.prototype.includes()`


Array.prototype[@@unscopables] - JavaScript

Array.prototype[@@unscopables]
==============================

The **`@@unscopables`** data property of `Array.prototype` is shared by all `Array` instances. It contains property names that were not included in the ECMAScript standard prior to the ES2015 version and that are ignored for `with` statement-binding purposes.

Value
-----

A `null`-prototype object with property names given below and their values set to `true`.

| Property attributes of `Array.prototype[@@unscopables]` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | yes |

Description
-----------

The default `Array` properties that are ignored for `with` statement-binding purposes are:

* `at()`
* `copyWithin()`
* `entries()`
* `fill()`
* `find()`
* `findIndex()`
* `findLast()`
* `findLastIndex()`
* `flat()`
* `flatMap()`
* `includes()`
* `keys()`
* `toReversed()`
* `toSorted()`
* `toSpliced()`
* `values()`

`Array.prototype[@@unscopables]` is an empty object only containing all the above property names with the value `true`. Its prototype is `null`, so `Object.prototype` properties like `toString` won't accidentally be made unscopable, and a `toString()` within the `with` statement will continue to be called on the array.

See `Symbol.unscopables` for how to set unscopable properties for your own objects.

Examples
--------

Imagine the `keys.push('something')` call below is in code that was written prior to ECMAScript 2015.

```js
var keys = [];

with (Array.prototype) {
  keys.push("something");
}
```

When ECMAScript 2015 introduced the `Array.prototype.keys()` method, if the `@@unscopables` data property had not also been introduced, that `keys.push('something')` call would break — because the JavaScript runtime would have interpreted `keys` as being the `Array.prototype.keys()` method, rather than the `keys` array defined in the example code.

So the `@@unscopables` data property for `Array.prototype` causes the `Array` properties introduced in ECMAScript 2015 to be ignored for `with` statement-binding purposes — allowing code that was written prior to ECMAScript 2015 to continue working as expected, rather than breaking.

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype-@@unscopables |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Array.prototype[@@unscopables]` in `core-js`
* Indexed collections guide
* `Array`
* `with`
* `Symbol.unscopables`


Array.prototype.findLastIndex() - JavaScript

Array.prototype.findLastIndex()
===============================

 The **`findLastIndex()`** method of `Array` instances iterates the array in reverse order and returns the index of the first element that satisfies the provided testing function.
 If no elements satisfy the testing function, -1 is returned.

See also the `findLast()` method, which returns the value of last element that satisfies the testing function (rather than its index).

Try it
------

Syntax
------

```js
findLastIndex(callbackFn)
findLastIndex(callbackFn, thisArg)
```

### Parameters

`callbackFn`

A function to execute for each element in the array. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments:

`element`

The current element being processed in the array.

`index`

The index of the current element being processed in the array.

`array`

The array `findLastIndex()` was called upon.

`thisArg` Optional

A value to use as `this` when executing `callbackFn`. See iterative methods.

### Return value

 The index of the last (highest-index) element in the array that passes the test.
 Otherwise `-1` if no matching element is found.

Description
-----------

The `findLastIndex()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array in descending-index order, until `callbackFn` returns a truthy value. `findLastIndex()` then returns the index of that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `findLastIndex()` returns `-1`. Read the iterative methods section for more information about how these methods work in general.

`callbackFn` is invoked for *every* index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as `undefined`.

The `findLastIndex()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties.

Examples
--------

### Find the index of the last prime number in an array

The following example returns the index of the last element in the array that is a prime number, or `-1` if there is no prime number.

```js
function isPrime(element) {
  if (element % 2 === 0 || element < 2) {
    return false;
  }
  for (let factor = 3; factor <= Math.sqrt(element); factor += 2) {
    if (element % factor === 0) {
      return false;
    }
  }
  return true;
}

console.log([4, 6, 8, 12].findLastIndex(isPrime)); // -1, not found
console.log([4, 5, 7, 8, 9, 11, 12].findLastIndex(isPrime)); // 5
```

### Using the third argument of callbackFn

The `array` argument is useful if you want to access another element in the array, especially when you don't have an existing variable that refers to the array. The following example first uses `filter()` to extract the positive values and then uses `findLastIndex()` to find the last element that is less than its neighbors.

```js
const numbers = [3, -1, 1, 4, 1, 5, 9, 2, 6];
const lastTrough = numbers
  .filter((num) => num > 0)
  .findLastIndex((num, idx, arr) => {
    // Without the arr argument, there's no way to easily access the
    // intermediate array without saving it to a variable.
    if (idx > 0 && num >= arr[idx - 1]) return false;
    if (idx < arr.length - 1 && num >= arr[idx + 1]) return false;
    return true;
  });
console.log(lastTrough); // 6
```

### Using findLastIndex() on sparse arrays

You can search for `undefined` in a sparse array and get the index of an empty slot.

```js
console.log([1, , 3].findLastIndex((x) => x === undefined)); // 1
```

### Calling findLastIndex() on non-array objects

The `findLastIndex()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`.

```js
const arrayLike = {
  length: 3,
  0: 2,
  1: 7.3,
  2: 4,
  3: 3, // ignored by findLastIndex() since length is 3
};
console.log(
  Array.prototype.findLastIndex.call(arrayLike, (x) => Number.isInteger(x)),
); // 2
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.findlastindex |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Array.prototype.findLastIndex` in `core-js`
* Indexed collections guide
* `Array`
* `Array.prototype.find()`
* `Array.prototype.findIndex()`
* `Array.prototype.findLast()`
* `Array.prototype.indexOf()`
* `Array.prototype.lastIndexOf()`
* `TypedArray.prototype.findLastIndex()`


Array.prototype.splice() - JavaScript

Array.prototype.splice()
========================

 The **`splice()`** method of `Array` instances changes the contents of an array by
 removing or replacing existing elements and/or adding new elements in place.

To create a new array with a segment removed and/or replaced without mutating the original array, use `toSpliced()`. To access part of an array without modifying it, see `slice()`.

Try it
------

Syntax
------

```js
splice(start)
splice(start, deleteCount)
splice(start, deleteCount, item1)
splice(start, deleteCount, item1, item2)
splice(start, deleteCount, item1, item2, /\* …, \*/ itemN)
```

### Parameters

`start`

Zero-based index at which to start changing the array, converted to an integer.

* Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used.
* If `start < -array.length`, `0` is used.
* If `start >= array.length`, no element will be deleted, but the method will behave as an adding function, adding as many elements as provided.
* If `start` is omitted (and `splice()` is called with no arguments), nothing is deleted. This is different from passing `undefined`, which is converted to `0`.

`deleteCount` Optional

An integer indicating the number of elements in the array to remove from `start`.

If `deleteCount` is omitted, or if its value is greater than or equal to the number of elements after the position specified by `start`, then all the elements from `start` to the end of the array will be deleted. However, if you wish to pass any `itemN` parameter, you should pass `Infinity` as `deleteCount` to delete all elements after `start`, because an explicit `undefined` gets converted to `0`.

 If `deleteCount` is `0` or negative, no elements are removed.
 In this case, you should specify at least one new element (see below).

`item1`, …, `itemN` Optional

The elements to add to the array, beginning from `start`.

If you do not specify any elements, `splice()` will only remove elements from the array.

### Return value

An array containing the deleted elements.

If only one element is removed, an array of one element is returned.

If no elements are removed, an empty array is returned.

Description
-----------

The `splice()` method is a mutating method. It may change the content of `this`. If the specified number of elements to insert differs from the number of elements being removed, the array's `length` will be changed as well. At the same time, it uses `@@species` to create a new array instance to be returned.

If the deleted portion is sparse, the array returned by `splice()` is sparse as well, with those corresponding indices being empty slots.

The `splice()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.

Examples
--------

### Remove 0 (zero) elements before index 2, and insert "drum"

```js
const myFish = ["angel", "clown", "mandarin", "sturgeon"];
const removed = myFish.splice(2, 0, "drum");

// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"]
// removed is [], no elements removed
```

### Remove 0 (zero) elements before index 2, and insert "drum" and "guitar"

```js
const myFish = ["angel", "clown", "mandarin", "sturgeon"];
const removed = myFish.splice(2, 0, "drum", "guitar");

// myFish is ["angel", "clown", "drum", "guitar", "mandarin", "sturgeon"]
// removed is [], no elements removed
```

### Remove 0 (zero) elements at index 0, and insert "angel"

`splice(0, 0, ...elements)` inserts elements at the start of the array like `unshift()`.

```js
const myFish = ["clown", "mandarin", "sturgeon"];
const removed = myFish.splice(0, 0, "angel");

// myFish is ["angel", "clown", "mandarin", "sturgeon"]
// no items removed
```

### Remove 0 (zero) elements at last index, and insert "sturgeon"

`splice(array.length, 0, ...elements)` inserts elements at the end of the array like `push()`.

```js
const myFish = ["angel", "clown", "mandarin"];
const removed = myFish.splice(myFish.length, 0, "sturgeon");

// myFish is ["angel", "clown", "mandarin", "sturgeon"]
// no items removed
```

### Remove 1 element at index 3

```js
const myFish = ["angel", "clown", "drum", "mandarin", "sturgeon"];
const removed = myFish.splice(3, 1);

// myFish is ["angel", "clown", "drum", "sturgeon"]
// removed is ["mandarin"]
```

### Remove 1 element at index 2, and insert "trumpet"

```js
const myFish = ["angel", "clown", "drum", "sturgeon"];
const removed = myFish.splice(2, 1, "trumpet");

// myFish is ["angel", "clown", "trumpet", "sturgeon"]
// removed is ["drum"]
```

### Remove 2 elements from index 0, and insert "parrot", "anemone" and "blue"

```js
const myFish = ["angel", "clown", "trumpet", "sturgeon"];
const removed = myFish.splice(0, 2, "parrot", "anemone", "blue");

// myFish is ["parrot", "anemone", "blue", "trumpet", "sturgeon"]
// removed is ["angel", "clown"]
```

### Remove 2 elements, starting from index 2

```js
const myFish = ["parrot", "anemone", "blue", "trumpet", "sturgeon"];
const removed = myFish.splice(2, 2);

// myFish is ["parrot", "anemone", "sturgeon"]
// removed is ["blue", "trumpet"]
```

### Remove 1 element from index -2

```js
const myFish = ["angel", "clown", "mandarin", "sturgeon"];
const removed = myFish.splice(-2, 1);

// myFish is ["angel", "clown", "sturgeon"]
// removed is ["mandarin"]
```

### Remove all elements, starting from index 2

```js
const myFish = ["angel", "clown", "mandarin", "sturgeon"];
const removed = myFish.splice(2);

// myFish is ["angel", "clown"]
// removed is ["mandarin", "sturgeon"]
```

### Using splice() on sparse arrays

The `splice()` method preserves the array's sparseness.

```js
const arr = [1, , 3, 4, , 6];
console.log(arr.splice(1, 2)); // [empty, 3]
console.log(arr); // [1, 4, empty, 6]
```

### Calling splice() on non-array objects

The `splice()` method reads the `length` property of `this`. It then updates the integer-keyed properties and the `length` property as needed.

```js
const arrayLike = {
  length: 3,
  unrelated: "foo",
  0: 5,
  2: 4,
};
console.log(Array.prototype.splice.call(arrayLike, 0, 1, 2, 3));
// [ 5 ]
console.log(arrayLike);
// { '0': 2, '1': 3, '3': 4, length: 4, unrelated: 'foo' }
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.splice |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Indexed collections guide
* `Array`
* `Array.prototype.concat()`
* `Array.prototype.push()`
* `Array.prototype.pop()`
* `Array.prototype.shift()`
* `Array.prototype.slice()`
* `Array.prototype.toSpliced()`
* `Array.prototype.unshift()`


Array.prototype.push() - JavaScript

Array.prototype.push()
======================

 The **`push()`** method of `Array` instances adds the specified elements to the end of
 an array and returns the new length of the array.

Try it
------

Syntax
------

```js
push()
push(element1)
push(element1, element2)
push(element1, element2, /\* …, \*/ elementN)
```

### Parameters

`element1`, …, `elementN`

The element(s) to add to the end of the array.

### Return value

The new `length` property of the object upon which the method was called.

Description
-----------

The `push()` method appends values to an array.

`Array.prototype.unshift()` has similar behavior to `push()`, but applied to the start of an array.

The `push()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with elements appended to the end, you can use `arr.concat([element0, element1, /* ... ,*/ elementN])` instead. Notice that the elements are wrapped in an extra array — otherwise, if the element is an array itself, it would be spread instead of pushed as a single element due to the behavior of `concat()`.

The `push()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.

Examples
--------

### Adding elements to an array

 The following code creates the `sports` array containing two elements, then
 appends two elements to it. The `total` variable contains the new length of
 the array.

```js
const sports = ["soccer", "baseball"];
const total = sports.push("football", "swimming");

console.log(sports); // ['soccer', 'baseball', 'football', 'swimming']
console.log(total); // 4
```

### Merging two arrays

 This example uses spread syntax to push all elements from a
 second array into the first one.

```js
const vegetables = ["parsnip", "potato"];
const moreVegs = ["celery", "beetroot"];

// Merge the second array into the first one
vegetables.push(...moreVegs);

console.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot']
```

Merging two arrays can also be done with the `concat()` method.

### Calling push() on non-array objects

The `push()` method reads the `length` property of `this`. It then sets each index of `this` starting at `length` with the arguments passed to `push()`. Finally, it sets the `length` to the previous length plus the number of pushed elements.

```js
const arrayLike = {
  length: 3,
  unrelated: "foo",
  2: 4,
};
Array.prototype.push.call(arrayLike, 1, 2);
console.log(arrayLike);
// { '2': 4, '3': 1, '4': 2, length: 5, unrelated: 'foo' }

const plainObj = {};
// There's no length property, so the length is 0
Array.prototype.push.call(plainObj, 1, 2);
console.log(plainObj);
// { '0': 1, '1': 2, length: 2 }
```

### Using an object in an array-like fashion

 As mentioned above, `push` is intentionally generic, and we can use that to
 our advantage. `Array.prototype.push` can work on an object just fine, as
 this example shows.

 Note that we don't create an array to store a collection of objects. Instead, we store
 the collection on the object itself and use `call` on
 `Array.prototype.push` to trick the method into thinking we are dealing with
 an array—and it just works, thanks to the way JavaScript allows us to establish the
 execution context in any way we want.

```js
const obj = {
  length: 0,

  addElem(elem) {
    // obj.length is automatically incremented
    // every time an element is added.
    [].push.call(this, elem);
  },
};

// Let's add some empty objects just to illustrate.
obj.addElem({});
obj.addElem({});
console.log(obj.length); // 2
```

 Note that although `obj` is not an array, the method `push`
 successfully incremented `obj`'s `length` property just like if we
 were dealing with an actual array.

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.push |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Array.prototype.push` in `core-js` with fixes of this method
* Indexed collections guide
* `Array`
* `Array.prototype.pop()`
* `Array.prototype.shift()`
* `Array.prototype.unshift()`
* `Array.prototype.concat()`
* `Array.prototype.splice()`


Array.prototype.unshift() - JavaScript

Array.prototype.unshift()
=========================

 The **`unshift()`** method of `Array` instances adds the specified elements to the
 beginning of an array and returns the new length of the array.

Try it
------

Syntax
------

```js
unshift()
unshift(element1)
unshift(element1, element2)
unshift(element1, element2, /\* …, \*/ elementN)
```

### Parameters

`element1`, …, `elementN`

The elements to add to the front of the `arr`.

### Return value

 The new `length` property of the object upon which the
 method was called.

Description
-----------

 The `unshift()` method inserts the given values to the beginning of an
 array-like object.

`Array.prototype.push()` has similar behavior to `unshift()`, but applied to the end of an array.

 Please note that, if multiple elements are passed as parameters, they're inserted in
 chunk at the beginning of the object, in the exact same order they were passed as
 parameters. Hence, calling `unshift()` with `n`
 arguments **once**, or calling it `n` times with
 **1** argument (with a loop, for example), don't yield the same results.

See example:

```js
let arr = [4, 5, 6];

arr.unshift(1, 2, 3);
console.log(arr);
// [1, 2, 3, 4, 5, 6]

arr = [4, 5, 6]; // resetting the array

arr.unshift(1);
arr.unshift(2);
arr.unshift(3);

console.log(arr);
// [3, 2, 1, 4, 5, 6]
```

The `unshift()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.

Examples
--------

### Using unshift()

```js
const arr = [1, 2];

arr.unshift(0); // result of the call is 3, which is the new array length
// arr is [0, 1, 2]

arr.unshift(-2, -1); // the new array length is 5
// arr is [-2, -1, 0, 1, 2]

arr.unshift([-4, -3]); // the new array length is 6
// arr is [[-4, -3], -2, -1, 0, 1, 2]

arr.unshift([-7, -6], [-5]); // the new array length is 8
// arr is [ [-7, -6], [-5], [-4, -3], -2, -1, 0, 1, 2 ]
```

### Calling unshift() on non-array objects

The `unshift()` method reads the `length` property of `this`. It shifts all indices in the range `0` to `length - 1` right by the number of arguments (incrementing their values by this number). Then, it sets each index starting at `0` with the arguments passed to `unshift()`. Finally, it sets the `length` to the previous length plus the number of prepended elements.

```js
const arrayLike = {
  length: 3,
  unrelated: "foo",
  2: 4,
};
Array.prototype.unshift.call(arrayLike, 1, 2);
console.log(arrayLike);
// { '0': 1, '1': 2, '4': 4, length: 5, unrelated: 'foo' }

const plainObj = {};
// There's no length property, so the length is 0
Array.prototype.unshift.call(plainObj, 1, 2);
console.log(plainObj);
// { '0': 1, '1': 2, length: 2 }
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.unshift |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Array.prototype.unshift` in `core-js` with fixes of this method
* Indexed collections guide
* `Array`
* `Array.prototype.push()`
* `Array.prototype.pop()`
* `Array.prototype.shift()`
* `Array.prototype.concat()`
* `Array.prototype.splice()`


Array.prototype.slice() - JavaScript

Array.prototype.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.

Try it
------

Syntax
------

```js
slice()
slice(start)
slice(start, end)
```

### Parameters

`start` Optional

Zero-based index at which to start extraction, converted to an integer.

* Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used.
* If `start < -array.length` or `start` is omitted, `0` is used.
* If `start >= array.length`, nothing is extracted.

`end` Optional

Zero-based index at which to end extraction, converted to an integer. `slice()` extracts up to but not including `end`.

* Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used.
* If `end < -array.length`, `0` is used.
* If `end >= array.length` or `end` is omitted, `array.length` is used, causing all elements until the end to be extracted.
* If `end` is positioned before or at `start` after normalization, nothing is extracted.

### Return value

A new array containing the extracted elements.

Description
-----------

The `slice()` method is a copying method. It does not alter `this` but instead returns a shallow copy that contains some of the same elements as the ones from the original array.

The `slice()` method preserves empty slots. If the sliced portion is sparse, the returned array is sparse as well.

The `slice()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties.

Examples
--------

### Return a portion of an existing array

```js
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(1, 3);

// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
// citrus contains ['Orange','Lemon']
```

### Using slice

 In the following example, `slice` creates a new array, `newCar`,
 from `myCar`. Both include a reference to the object `myHonda`.
 When the color of `myHonda` is changed to purple, both arrays reflect the
 change.

```js
// Using slice, create newCar from myCar.
const myHonda = {
  color: "red",
  wheels: 4,
  engine: { cylinders: 4, size: 2.2 },
};
const myCar = [myHonda, 2, "cherry condition", "purchased 1997"];
const newCar = myCar.slice(0, 2);

console.log("myCar =", myCar);
console.log("newCar =", newCar);
console.log("myCar[0].color =", myCar[0].color);
console.log("newCar[0].color =", newCar[0].color);

// Change the color of myHonda.
myHonda.color = "purple";
console.log("The new color of my Honda is", myHonda.color);

console.log("myCar[0].color =", myCar[0].color);
console.log("newCar[0].color =", newCar[0].color);
```

This script writes:
```

myCar = [
  { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } },
  2,
  'cherry condition',
  'purchased 1997'
]
newCar = [ { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } }, 2 ]
myCar[0].color = red
newCar[0].color = red
The new color of my Honda is purple
myCar[0].color = purple
newCar[0].color = purple
```

### Calling slice() on non-array objects

The `slice()` method reads the `length` property of `this`. It then reads the integer-keyed properties from `start` to `end` and defines them on a newly created array.

```js
const arrayLike = {
  length: 3,
  0: 2,
  1: 3,
  2: 4,
  3: 33, // ignored by slice() since length is 3
};
console.log(Array.prototype.slice.call(arrayLike, 1, 3));
// [ 3, 4 ]
```

### Using slice() to convert array-like objects to arrays

The `slice()` method is often used with `bind()` and `call()` to create a utility method that converts an array-like object into an array.

```js
// slice() is called with `this` passed as the first argument
const slice = Function.prototype.call.bind(Array.prototype.slice);

function list() {
  return slice(arguments);
}

const list1 = list(1, 2, 3); // [1, 2, 3]
```

### Using slice() on sparse arrays

The array returned from `slice()` may be sparse if the source is sparse.

```js
console.log([1, 2, , 4, 5].slice(1, 4)); // [2, empty, 4]
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.slice |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Array.prototype.slice` in `core-js`
* Indexed collections guide
* `Array`
* `Array.prototype.pop()`
* `Array.prototype.shift()`
* `Array.prototype.concat()`
* `Array.prototype.splice()`
* `TypedArray.prototype.slice()`
* `String.prototype.slice()`


Array.prototype.filter() - JavaScript

Array.prototype.filter()
========================

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.

Try it
------

Syntax
------

```js
filter(callbackFn)
filter(callbackFn, thisArg)
```

### Parameters

`callbackFn`

A function to execute for each element in the array. It should return a truthy value to keep the element in the resulting array, and a falsy value otherwise. The function is called with the following arguments:

`element`

The current element being processed in the array.

`index`

The index of the current element being processed in the array.

`array`

The array `filter()` was called upon.

`thisArg` Optional

A value to use as `this` when executing `callbackFn`. See iterative methods.

### Return value

A shallow copy of the given array containing just the elements that pass the test. If no elements pass the test, an empty array is returned.

Description
-----------

The `filter()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, and constructs a new array of all the values for which `callbackFn` returns a truthy value. Array elements which do not pass the `callbackFn` test are not included in the new array. Read the iterative methods section for more information about how these methods work in general.

`callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays.

The `filter()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties.

Examples
--------

### Filtering out all small values

The following example uses `filter()` to create a filtered array that has all elements with values less than 10 removed.

```js
function isBigEnough(value) {
  return value >= 10;
}

const filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]
```

### Find all prime numbers in an array

The following example returns all prime numbers in the array:

```js
const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];

function isPrime(num) {
  for (let i = 2; num > i; i++) {
    if (num % i === 0) {
      return false;
    }
  }
  return num > 1;
}

console.log(array.filter(isPrime)); // [2, 3, 5, 7, 11, 13]
```

### Filtering invalid entries from JSON

The following example uses `filter()` to create a filtered JSON of all elements with non-zero, numeric `id`.

```js
const arr = [
  { id: 15 },
  { id: -1 },
  { id: 0 },
  { id: 3 },
  { id: 12.2 },
  {},
  { id: null },
  { id: NaN },
  { id: "undefined" },
];

let invalidEntries = 0;

function filterByID(item) {
  if (Number.isFinite(item.id) && item.id !== 0) {
    return true;
  }
  invalidEntries++;
  return false;
}

const arrByID = arr.filter(filterByID);

console.log("Filtered Array\n", arrByID);
// Filtered Array
// [{ id: 15 }, { id: -1 }, { id: 3 }, { id: 12.2 }]

console.log("Number of Invalid Entries =", invalidEntries);
// Number of Invalid Entries = 5
```

### Searching in array

Following example uses `filter()` to filter array content based on search criteria.

```js
const fruits = ["apple", "banana", "grapes", "mango", "orange"];

/\*\*
 \* Filter array items based on search criteria (query)
 \*/
function filterItems(arr, query) {
  return arr.filter((el) => el.toLowerCase().includes(query.toLowerCase()));
}

console.log(filterItems(fruits, "ap")); // ['apple', 'grapes']
console.log(filterItems(fruits, "an")); // ['banana', 'mango', 'orange']
```

### Using the third argument of callbackFn

The `array` argument is useful if you want to access another element in the array, especially when you don't have an existing variable that refers to the array. The following example first uses `map()` to extract the numerical ID from each name and then uses `filter()` to select the ones that are greater than its neighbors.

```js
const names = ["JC63", "Bob132", "Ursula89", "Ben96"];
const greatIDs = names
  .map((name) => parseInt(name.match(/[0-9]+/)[0], 10))
  .filter((id, idx, arr) => {
    // Without the arr argument, there's no way to easily access the
    // intermediate array without saving it to a variable.
    if (idx > 0 && id <= arr[idx - 1]) return false;
    if (idx < arr.length - 1 && id <= arr[idx + 1]) return false;
    return true;
  });
console.log(greatIDs); // [132, 96]
```

The `array` argument is *not* the array that is being built — there is no way to access the array being built from the callback function.

### Using filter() on sparse arrays

`filter()` will skip empty slots.

```js
console.log([1, , undefined].filter((x) => x === undefined)); // [undefined]
console.log([1, , undefined].filter((x) => x !== 2)); // [1, undefined]
```

### Calling filter() on non-array objects

The `filter()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`.

```js
const arrayLike = {
  length: 3,
  0: "a",
  1: "b",
  2: "c",
  3: "a", // ignored by filter() since length is 3
};
console.log(Array.prototype.filter.call(arrayLike, (x) => x <= "b"));
// [ 'a', 'b' ]
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.filter |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Array.prototype.filter` in `core-js`
* Indexed collections guide
* `Array`
* `Array.prototype.forEach()`
* `Array.prototype.every()`
* `Array.prototype.map()`
* `Array.prototype.some()`
* `Array.prototype.reduce()`
* `TypedArray.prototype.filter()`


Array.prototype.keys() - JavaScript

Array.prototype.keys()
======================

The **`keys()`** method of `Array` instances returns a new *array iterator* object that contains the keys for each index in the array.

Try it
------

Syntax
------

```js
keys()
```

### Parameters

None.

### Return value

A new iterable iterator object.

Description
-----------

When used on sparse arrays, the `keys()` method iterates empty slots as if they have the value `undefined`.

The `keys()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties.

Examples
--------

### Using keys() on sparse arrays

Unlike `Object.keys()`, which only includes keys that actually exist in the array, the `keys()` iterator doesn't ignore holes representing missing properties.

```js
const arr = ["a", , "c"];
const sparseKeys = Object.keys(arr);
const denseKeys = [...arr.keys()];
console.log(sparseKeys); // ['0', '2']
console.log(denseKeys); // [0, 1, 2]
```

### Calling keys() on non-array objects

The `keys()` method reads the `length` property of `this` and then yields all integer indices between 0 and `length - 1`. No index access actually happens.

```js
const arrayLike = {
  length: 3,
};
for (const entry of Array.prototype.keys.call(arrayLike)) {
  console.log(entry);
}
// 0
// 1
// 2
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.keys |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Array.prototype.keys` in `core-js`
* Indexed collections guide
* `Array`
* `Array.prototype.entries()`
* `Array.prototype.values()`
* `Array.prototype[@@iterator]()`
* `TypedArray.prototype.keys()`
* Iteration protocols


Array.prototype.values() - JavaScript

Array.prototype.values()
========================

The **`values()`** method of `Array` instances returns a new *array iterator* object that iterates the value of each item in the array.

Try it
------

Syntax
------

```js
values()
```

### Parameters

None.

### Return value

A new iterable iterator object.

Description
-----------

`Array.prototype.values()` is the default implementation of `Array.prototype[@@iterator]()`.

```js
Array.prototype.values === Array.prototype[Symbol.iterator]; // true
```

When used on sparse arrays, the `values()` method iterates empty slots as if they have the value `undefined`.

The `values()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties.

Examples
--------

### Iteration using for...of loop

Because `values()` returns an iterable iterator, you can use a `for...of` loop to iterate it.

```js
const arr = ["a", "b", "c", "d", "e"];
const iterator = arr.values();

for (const letter of iterator) {
  console.log(letter);
} // "a" "b" "c" "d" "e"
```

### Iteration using next()

Because the return value is also an iterator, you can directly call its `next()` method.

```js
const arr = ["a", "b", "c", "d", "e"];
const iterator = arr.values();
iterator.next(); // { value: "a", done: false }
iterator.next(); // { value: "b", done: false }
iterator.next(); // { value: "c", done: false }
iterator.next(); // { value: "d", done: false }
iterator.next(); // { value: "e", done: false }
iterator.next(); // { value: undefined, done: true }
console.log(iterator.next().value); // undefined
```

### Reusing the iterable

**Warning:** The array iterator object should be a one-time use object. Do not reuse it.

The iterable returned from `values()` is not reusable. When `next().done = true` or `currentIndex > length`, the `for...of` loop ends, and further iterating it has no effect.

```js
const arr = ["a", "b", "c", "d", "e"];
const values = arr.values();
for (const letter of values) {
  console.log(letter);
}
// "a" "b" "c" "d" "e"
for (const letter of values) {
  console.log(letter);
}
// undefined
```

If you use a `break` statement to end the iteration early, the iterator can resume from the current position when continuing to iterate it.

```js
const arr = ["a", "b", "c", "d", "e"];
const values = arr.values();
for (const letter of values) {
  console.log(letter);
  if (letter === "b") {
    break;
  }
}
// "a" "b"

for (const letter of values) {
  console.log(letter);
}
// "c" "d" "e"
```

### Mutations during iteration

There are no values stored in the array iterator object returned from `values()`; instead, it stores the address of the array used in its creation, and reads the currently visited index on each iteration. Therefore, its iteration output depends on the value stored in that index at the time of stepping. If the values in the array changed, the array iterator object's values change too.

```js
const arr = ["a", "b", "c", "d", "e"];
const iterator = arr.values();
console.log(iterator); // Array Iterator { }
console.log(iterator.next().value); // "a"
arr[1] = "n";
console.log(iterator.next().value); // "n"
```

### Iterating sparse arrays

`values()` will visit empty slots as if they are `undefined`.

```js
for (const element of [, "a"].values()) {
  console.log(element);
}
// undefined
// 'a'
```

### Calling values() on non-array objects

The `values()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`.

```js
const arrayLike = {
  length: 3,
  0: "a",
  1: "b",
  2: "c",
  3: "d", // ignored by values() since length is 3
};
for (const entry of Array.prototype.values.call(arrayLike)) {
  console.log(entry);
}
// a
// b
// c
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.values |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Array.prototype.values` in `core-js`
* Indexed collections guide
* `Array`
* `Array.prototype.entries()`
* `Array.prototype.keys()`
* `Array.prototype[@@iterator]()`
* `TypedArray.prototype.values()`
* Iteration protocols


Array.prototype[@@iterator]() - JavaScript

Array.prototype[@@iterator]()
=============================

The **`[@@iterator]()`** method of `Array` instances implements the iterable protocol and allows arrays to be consumed by most syntaxes expecting iterables, such as the spread syntax and `for...of` loops. It returns an array iterator object that yields the value of each index in the array.

The initial value of this property is the same function object as the initial value of the `Array.prototype.values` property.

Try it
------

Syntax
------

```js
array[Symbol.iterator]()
```

### Parameters

None.

### Return value

The same return value as `Array.prototype.values()`: a new iterable iterator object that yields the value of each index in the array.

Examples
--------

### Iteration using for...of loop

Note that you seldom need to call this method directly. The existence of the `@@iterator` method makes arrays iterable, and iterating syntaxes like the `for...of` loop automatically call this method to obtain the iterator to loop over.

#### HTML

```html
<ul id="letterResult"></ul>
```

#### JavaScript

```js
const arr = ["a", "b", "c"];
const letterResult = document.getElementById("letterResult");
for (const letter of arr) {
  const li = document.createElement("li");
  li.textContent = letter;
  letterResult.appendChild(li);
}
```

#### Result

### Manually hand-rolling the iterator

You may still manually call the `next()` method of the returned iterator object to achieve maximum control over the iteration process.

```js
const arr = ["a", "b", "c", "d", "e"];
const arrIter = arr[Symbol.iterator]();
console.log(arrIter.next().value); // a
console.log(arrIter.next().value); // b
console.log(arrIter.next().value); // c
console.log(arrIter.next().value); // d
console.log(arrIter.next().value); // e
```

### Handling strings and string arrays with the same function

Because both strings and arrays implement the iterable protocol, a generic function can be designed to handle both inputs in the same fashion. This is better than calling `Array.prototype.values()` directly, which requires the input to be an array, or at least an object with such a method.

```js
function logIterable(it) {
  if (typeof it[Symbol.iterator] !== "function") {
    console.log(it, "is not iterable.");
    return;
  }
  for (const letter of it) {
    console.log(letter);
  }
}

// Array
logIterable(["a", "b", "c"]);
// a
// b
// c

// String
logIterable("abc");
// a
// b
// c

// Number
logIterable(123);
// 123 is not iterable.
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype-@@iterator |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Array.prototype[@@iterator]` in `core-js`
* Indexed collections guide
* `Array`
* `Array.prototype.keys()`
* `Array.prototype.entries()`
* `Array.prototype.values()`
* `TypedArray.prototype[@@iterator]()`
* `String.prototype[@@iterator]()`
* `Symbol.iterator`
* Iteration protocols


Array: length - JavaScript

Array: length
=============

The **`length`** data property of an `Array` instance represents the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.

Try it
------

Value
-----

A nonnegative integer less than 232.

| Property attributes of `Array: length` |
| --- |
| Writable | yes |
| Enumerable | no |
| Configurable | no |

Description
-----------

The value of the `length` property is a nonnegative integer with a value less than 232.

```js
const listA = [1, 2, 3];
const listB = new Array(6);

console.log(listA.length);
// 3

console.log(listB.length);
// 6

listB.length = 2 \*\* 32; // 4294967296
// RangeError: Invalid array length

const listC = new Array(-100); // Negative numbers are not allowed
// RangeError: Invalid array length
```

The array object observes the `length` property, and automatically syncs the `length` value with the array's content. This means:

* Setting `length` to a value smaller than the current length truncates the array — elements beyond the new `length` are deleted.
* Setting any array index (a nonnegative integer smaller than 232) beyond the current `length` extends the array — the `length` property is increased to reflect the new highest index.
* Setting `length` to an invalid value (e.g. a negative number or a non-integer) throws a `RangeError` exception.

When `length` is set to a bigger value than the current length, the array is extended by adding empty slots, not actual `undefined` values. Empty slots have some special interactions with array methods; see array methods and empty slots.

```js
const arr = [1, 2];
console.log(arr);
// [ 1, 2 ]

arr.length = 5; // set array length to 5 while currently 2.
console.log(arr);
// [ 1, 2, <3 empty items> ]

arr.forEach((element) => console.log(element));
// 1
// 2
```

See also Relationship between `length` and numerical properties.

Examples
--------

### Iterating over an array

In the following example, the array `numbers` is iterated through by looking at the `length` property. The value in each element is then doubled.

```js
const numbers = [1, 2, 3, 4, 5];
const length = numbers.length;
for (let i = 0; i < length; i++) {
  numbers[i] \*= 2;
}
// numbers is now [2, 4, 6, 8, 10]
```

### Shortening an array

The following example shortens the array `numbers` to a length of 3 if the current length is greater than 3.

```js
const numbers = [1, 2, 3, 4, 5];

if (numbers.length > 3) {
  numbers.length = 3;
}

console.log(numbers); // [1, 2, 3]
console.log(numbers.length); // 3
console.log(numbers[3]); // undefined; the extra elements are deleted
```

### Create empty array of fixed length

Setting `length` to a value greater than the current length creates a sparse array.

```js
const numbers = [];
numbers.length = 3;
console.log(numbers); // [empty x 3]
```

### Array with non-writable length

The `length` property is automatically updated by the array when elements are added beyond the current length. If the `length` property is made non-writable, the array will not be able to update it. This causes an error in strict mode.

```js
"use strict";

const numbers = [1, 2, 3, 4, 5];
Object.defineProperty(numbers, "length", { writable: false });
numbers[5] = 6; // TypeError: Cannot assign to read only property 'length' of object '[object Array]'
numbers.push(5); // // TypeError: Cannot assign to read only property 'length' of object '[object Array]'
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-properties-of-array-instances-length |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Indexed collections guide
* `Array`
* `TypedArray.prototype.length`
* `String`: `length`
* RangeError: invalid array length


Array.prototype.some() - JavaScript

Array.prototype.some()
======================

 The **`some()`** method of `Array` instances tests whether
 at least one element in the array passes the test implemented by the provided
 function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array.

Try it
------

Syntax
------

```js
some(callbackFn)
some(callbackFn, thisArg)
```

### Parameters

`callbackFn`

A function to execute for each element in the array. It should return a truthy value to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments:

`element`

The current element being processed in the array.

`index`

The index of the current element being processed in the array.

`array`

The array `some()` was called upon.

`thisArg` Optional

A value to use as `this` when executing `callbackFn`. See iterative methods.

### Return value

`false` unless `callbackFn` returns a truthy value for an array element, in which case `true` is immediately returned.

Description
-----------

The `some()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, until the `callbackFn` returns a truthy value. If such an element is found, `some()` immediately returns `true` and stops iterating through the array. Otherwise, if `callbackFn` returns a falsy value for all elements, `some()` returns `false`. Read the iterative methods section for more information about how these methods work in general.

`some()` acts like the "there exists" quantifier in mathematics. In particular, for an empty array, it returns `false` for any condition.

`callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays.

`some()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved *before* the first invocation of `callbackFn`. Therefore:

* `callbackFn` will not visit any elements added beyond the array's initial length when the call to `some()` began.
* Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again.
* If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. Deleted elements are not visited.

**Warning:** Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).

The `some()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties.

Examples
--------

### Testing value of array elements

The following example tests whether any element in the array is bigger than 10.

```js
function isBiggerThan10(element, index, array) {
  return element > 10;
}

[2, 5, 8, 1, 4].some(isBiggerThan10); // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true
```

### Testing array elements using arrow functions

Arrow functions
 provide a shorter syntax for the same test.

```js
[2, 5, 8, 1, 4].some((x) => x > 10); // false
[12, 5, 8, 1, 4].some((x) => x > 10); // true
```

### Checking whether a value exists in an array

To mimic the function of the `includes()` method, this custom function returns `true` if the element exists in the array:

```js
const fruits = ["apple", "banana", "mango", "guava"];

function checkAvailability(arr, val) {
  return arr.some((arrVal) => val === arrVal);
}

checkAvailability(fruits, "kela"); // false
checkAvailability(fruits, "banana"); // true
```

### Converting any value to Boolean

```js
const TRUTHY\_VALUES = [true, "true", 1];

function getBoolean(value) {
  if (typeof value === "string") {
    value = value.toLowerCase().trim();
  }

  return TRUTHY\_VALUES.some((t) => t === value);
}

getBoolean(false); // false
getBoolean("false"); // false
getBoolean(1); // true
getBoolean("true"); // true
```

### Using the third argument of callbackFn

The `array` argument is useful if you want to access another element in the array, especially when you don't have an existing variable that refers to the array. The following example first uses `filter()` to extract the positive values and then uses `some()` to check whether the array is strictly increasing.

```js
const numbers = [3, -1, 1, 4, 1, 5];
const isIncreasing = !numbers
  .filter((num) => num > 0)
  .some((num, idx, arr) => {
    // Without the arr argument, there's no way to easily access the
    // intermediate array without saving it to a variable.
    if (idx === 0) return false;
    return num <= arr[idx - 1];
  });
console.log(isIncreasing); // false
```

### Using some() on sparse arrays

`some()` will not run its predicate on empty slots.

```js
console.log([1, , 3].some((x) => x === undefined)); // false
console.log([1, , 1].some((x) => x !== 1)); // false
console.log([1, undefined, 1].some((x) => x !== 1)); // true
```

### Calling some() on non-array objects

The `some()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length` until they all have been accessed or `callbackFn` returns `true`.

```js
const arrayLike = {
  length: 3,
  0: "a",
  1: "b",
  2: "c",
  3: 3, // ignored by some() since length is 3
};
console.log(Array.prototype.some.call(arrayLike, (x) => typeof x === "number"));
// false
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.some |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Array.prototype.some` in `core-js`
* Indexed collections guide
* `Array`
* `Array.prototype.every()`
* `Array.prototype.forEach()`
* `Array.prototype.find()`
* `Array.prototype.includes()`
* `TypedArray.prototype.some()`


Array.prototype.forEach() - JavaScript

Array.prototype.forEach()
=========================

 The **`forEach()`** method of `Array` instances executes a provided function once
 for each array element.

Try it
------

Syntax
------

```js
forEach(callbackFn)
forEach(callbackFn, thisArg)
```

### Parameters

`callbackFn`

A function to execute for each element in the array. Its return value is discarded. The function is called with the following arguments:

`element`

The current element being processed in the array.

`index`

The index of the current element being processed in the array.

`array`

The array `forEach()` was called upon.

`thisArg` Optional

A value to use as `this` when executing `callbackFn`. See iterative methods.

### Return value

None (`undefined`).

Description
-----------

The `forEach()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order. Unlike `map()`, `forEach()` always returns `undefined` and is not chainable. The typical use case is to execute side effects at the end of a chain. Read the iterative methods section for more information about how these methods work in general.

`callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays.

The `forEach()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties.

There is no way to stop or break a `forEach()` loop other than by throwing an exception. If you need such behavior, the `forEach()` method is the wrong tool.

Early termination may be accomplished with looping statements like `for`, `for...of`, and `for...in`. Array methods like `every()`, `some()`, `find()`, and `findIndex()` also stops iteration immediately when further iteration is not necessary.

`forEach()` expects a synchronous function — it does not wait for promises. Make sure you are aware of the implications while using promises (or async functions) as `forEach` callbacks.

```js
const ratings = [5, 4, 5];
let sum = 0;

const sumFunction = async (a, b) => a + b;

ratings.forEach(async (rating) => {
  sum = await sumFunction(sum, rating);
});

console.log(sum);
// Naively expected output: 14
// Actual output: 0
```

To run a series of asynchronous operations sequentially or concurrently, see promise composition.

Examples
--------

### Converting a for loop to forEach

```js
const items = ["item1", "item2", "item3"];
const copyItems = [];

// before
for (let i = 0; i < items.length; i++) {
  copyItems.push(items[i]);
}

// after
items.forEach((item) => {
  copyItems.push(item);
});
```

### Printing the contents of an array

**Note:** In order to display the content of an array in the console,
 you can use `console.table()`, which prints a formatted
 version of the array.

 The following example illustrates an alternative approach, using
 `forEach()`.

The following code logs a line for each element in an array:

```js
const logArrayElements = (element, index /\*, array \*/) => {
  console.log(`a[${index}] = ${element}`);
};

// Notice that index 2 is skipped, since there is no item at
// that position in the array.
[2, 5, , 9].forEach(logArrayElements);
// Logs:
// a[0] = 2
// a[1] = 5
// a[3] = 9
```

### Using thisArg

 The following (contrived) example updates an object's properties from each entry in the
 array:

```js
class Counter {
  constructor() {
    this.sum = 0;
    this.count = 0;
  }
  add(array) {
    // Only function expressions have their own this bindings.
    array.forEach(function countEntry(entry) {
      this.sum += entry;
      ++this.count;
    }, this);
  }
}

const obj = new Counter();
obj.add([2, 5, 9]);
console.log(obj.count); // 3
console.log(obj.sum); // 16
```

 Since the `thisArg` parameter (`this`) is provided to
 `forEach()`, it is passed to `callback` each time it's
 invoked. The callback uses it as its `this` value.

**Note:** If passing the callback function used an
 arrow function expression,
 the `thisArg` parameter could be omitted,
 since all arrow functions lexically bind the `this`
 value.

### An object copy function

The following code creates a copy of a given object.

 There are different ways to create a copy of an object. The following is just one way
 and is presented to explain how `Array.prototype.forEach()` works by using
 `Object.*` utility functions.

```js
const copy = (obj) => {
  const copy = Object.create(Object.getPrototypeOf(obj));
  const propNames = Object.getOwnPropertyNames(obj);
  propNames.forEach((name) => {
    const desc = Object.getOwnPropertyDescriptor(obj, name);
    Object.defineProperty(copy, name, desc);
  });
  return copy;
};

const obj1 = { a: 1, b: 2 };
const obj2 = copy(obj1); // obj2 looks like obj1 now
```

### Flatten an array

 The following example is only here for learning purpose. If you want to flatten an
 array using built-in methods, you can use `Array.prototype.flat()`.

```js
const flatten = (arr) => {
  const result = [];
  arr.forEach((item) => {
    if (Array.isArray(item)) {
      result.push(...flatten(item));
    } else {
      result.push(item);
    }
  });
  return result;
};

// Usage
const nested = [1, 2, 3, [4, 5, [6, 7], 8, 9]];
console.log(flatten(nested)); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
```

### Using the third argument of callbackFn

The `array` argument is useful if you want to access another element in the array, especially when you don't have an existing variable that refers to the array. The following example first uses `filter()` to extract the positive values and then uses `forEach()` to log its neighbors.

```js
const numbers = [3, -1, 1, 4, 1, 5];
numbers
  .filter((num) => num > 0)
  .forEach((num, idx, arr) => {
    // Without the arr argument, there's no way to easily access the
    // intermediate array without saving it to a variable.
    console.log(arr[idx - 1], num, arr[idx + 1]);
  });
// undefined 3 1
// 3 1 4
// 1 4 1
// 4 1 5
// 1 5 undefined
```

### Using forEach() on sparse arrays

```js
const arraySparse = [1, 3, /\* empty \*/, 7];
let numCallbackRuns = 0;

arraySparse.forEach((element) => {
  console.log({ element });
  numCallbackRuns++;
});

console.log({ numCallbackRuns });

// { element: 1 }
// { element: 3 }
// { element: 7 }
// { numCallbackRuns: 3 }
```

The callback function is not invoked for the missing value at index 2.

### Calling forEach() on non-array objects

The `forEach()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`.

```js
const arrayLike = {
  length: 3,
  0: 2,
  1: 3,
  2: 4,
  3: 5, // ignored by forEach() since length is 3
};
Array.prototype.forEach.call(arrayLike, (x) => console.log(x));
// 2
// 3
// 4
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.foreach |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Array.prototype.forEach` in `core-js`
* Indexed collections guide
* `Array`
* `Array.prototype.find()`
* `Array.prototype.map()`
* `Array.prototype.filter()`
* `Array.prototype.every()`
* `Array.prototype.some()`
* `TypedArray.prototype.forEach()`
* `Map.prototype.forEach()`
* `Set.prototype.forEach()`


Array.prototype.find() - JavaScript

Array.prototype.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.

* If you need the **index** of the found element in the array, use `findIndex()`.
* If you need to find the **index of a value**, use `indexOf()`.
 (It's similar to `findIndex()`, but checks each element for equality with the value instead of using a testing function.)
* If you need to find if a value **exists** in an array, use `includes()`.
 Again, it checks each element for equality with the value instead of using a testing function.
* If you need to find if any element satisfies the provided testing function, use `some()`.
Try it
------

Syntax
------

```js
find(callbackFn)
find(callbackFn, thisArg)
```

### Parameters

`callbackFn`

A function to execute for each element in the array. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments:

`element`

The current element being processed in the array.

`index`

The index of the current element being processed in the array.

`array`

The array `find()` was called upon.

`thisArg` Optional

A value to use as `this` when executing `callbackFn`. See iterative methods.

### Return value

 The first element in the array that satisfies the provided testing function.
 Otherwise, `undefined` is returned.

Description
-----------

The `find()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order, until `callbackFn` returns a truthy value. `find()` then returns that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `find()` returns `undefined`. Read the iterative methods section for more information about how these methods work in general.

`callbackFn` is invoked for *every* index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as `undefined`.

The `find()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties.

Examples
--------

### Find an object in an array by one of its properties

```js
const inventory = [
  { name: "apples", quantity: 2 },
  { name: "bananas", quantity: 0 },
  { name: "cherries", quantity: 5 },
];

function isCherries(fruit) {
  return fruit.name === "cherries";
}

console.log(inventory.find(isCherries));
// { name: 'cherries', quantity: 5 }
```

#### Using arrow function and destructuring

```js
const inventory = [
  { name: "apples", quantity: 2 },
  { name: "bananas", quantity: 0 },
  { name: "cherries", quantity: 5 },
];

const result = inventory.find(({ name }) => name === "cherries");

console.log(result); // { name: 'cherries', quantity: 5 }
```

### Find a prime number in an array

The following example finds an element in the array that is a prime number (or returns `undefined` if there is no prime number):

```js
function isPrime(element, index, array) {
  let start = 2;
  while (start <= Math.sqrt(element)) {
    if (element % start++ < 1) {
      return false;
    }
  }
  return element > 1;
}

console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found
console.log([4, 5, 8, 12].find(isPrime)); // 5
```

### Using the third argument of callbackFn

The `array` argument is useful if you want to access another element in the array, especially when you don't have an existing variable that refers to the array. The following example first uses `filter()` to extract the positive values and then uses `find()` to find the first element that is less than its neighbors.

```js
const numbers = [3, -1, 1, 4, 1, 5, 9, 2, 6];
const firstTrough = numbers
  .filter((num) => num > 0)
  .find((num, idx, arr) => {
    // Without the arr argument, there's no way to easily access the
    // intermediate array without saving it to a variable.
    if (idx > 0 && num >= arr[idx - 1]) return false;
    if (idx < arr.length - 1 && num >= arr[idx + 1]) return false;
    return true;
  });
console.log(firstTrough); // 1
```

### Using find() on sparse arrays

Empty slots in sparse arrays *are* visited, and are treated the same as `undefined`.

```js
// Declare array with no elements at indexes 2, 3, and 4
const array = [0, 1, , , , 5, 6];

// Shows all indexes, not just those with assigned values
array.find((value, index) => {
  console.log("Visited index", index, "with value", value);
});
// Visited index 0 with value 0
// Visited index 1 with value 1
// Visited index 2 with value undefined
// Visited index 3 with value undefined
// Visited index 4 with value undefined
// Visited index 5 with value 5
// Visited index 6 with value 6

// Shows all indexes, including deleted
array.find((value, index) => {
  // Delete element 5 on first iteration
  if (index === 0) {
    console.log("Deleting array[5] with value", array[5]);
    delete array[5];
  }
  // Element 5 is still visited even though deleted
  console.log("Visited index", index, "with value", value);
});
// Deleting array[5] with value 5
// Visited index 0 with value 0
// Visited index 1 with value 1
// Visited index 2 with value undefined
// Visited index 3 with value undefined
// Visited index 4 with value undefined
// Visited index 5 with value undefined
// Visited index 6 with value 6
```

### Calling find() on non-array objects

The `find()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`.

```js
const arrayLike = {
  length: 3,
  "-1": 0.1, // ignored by find() since -1 < 0
  0: 2,
  1: 7.3,
  2: 4,
};
console.log(Array.prototype.find.call(arrayLike, (x) => !Number.isInteger(x)));
// 7.3
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.find |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Array.prototype.find` in `core-js`
* Indexed collections guide
* `Array`
* `Array.prototype.findIndex()`
* `Array.prototype.findLast()`
* `Array.prototype.findLastIndex()`
* `Array.prototype.includes()`
* `Array.prototype.filter()`
* `Array.prototype.every()`
* `Array.prototype.some()`
* `TypedArray.prototype.find()`


Array.prototype.indexOf() - JavaScript

Array.prototype.indexOf()
=========================

 The **`indexOf()`** method of `Array` instances returns the first index at which a
 given element can be found in the array, or -1 if it is not present.

Try it
------

Syntax
------

```js
indexOf(searchElement)
indexOf(searchElement, fromIndex)
```

### Parameters

`searchElement`

Element to locate in the array.

`fromIndex` Optional

Zero-based index at which to start searching, converted to an integer.

* Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. Note, the array is still searched from front to back in this case.
* If `fromIndex < -array.length` or `fromIndex` is omitted, `0` is used, causing the entire array to be searched.
* If `fromIndex >= array.length`, the array is not searched and `-1` is returned.

### Return value

The first index of `searchElement` in the array; `-1` if not found.

Description
-----------

The `indexOf()` method compares `searchElement` to elements of the array using strict equality (the same algorithm used by the `===` operator). `NaN` values are never compared as equal, so `indexOf()` always returns `-1` when `searchElement` is `NaN`.

The `indexOf()` method skips empty slots in sparse arrays.

The `indexOf()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties.

Examples
--------

### Using indexOf()

The following example uses `indexOf()` to locate values in an array.

```js
const array = [2, 9, 9];
array.indexOf(2); // 0
array.indexOf(7); // -1
array.indexOf(9, 2); // 2
array.indexOf(2, -1); // -1
array.indexOf(2, -3); // 0
```

You cannot use `indexOf()` to search for `NaN`.

```js
const array = [NaN];
array.indexOf(NaN); // -1
```

### Finding all the occurrences of an element

```js
const indices = [];
const array = ["a", "b", "a", "c", "a", "d"];
const element = "a";
let idx = array.indexOf(element);
while (idx !== -1) {
  indices.push(idx);
  idx = array.indexOf(element, idx + 1);
}
console.log(indices);
// [0, 2, 4]
```

### Finding if an element exists in the array or not and updating the array

```js
function updateVegetablesCollection(veggies, veggie) {
  if (veggies.indexOf(veggie) === -1) {
    veggies.push(veggie);
    console.log(`New veggies collection is: ${veggies}`);
  } else {
    console.log(`${veggie} already exists in the veggies collection.`);
  }
}

const veggies = ["potato", "tomato", "chillies", "green-pepper"];

updateVegetablesCollection(veggies, "spinach");
// New veggies collection is: potato,tomato,chillies,green-pepper,spinach
updateVegetablesCollection(veggies, "spinach");
// spinach already exists in the veggies collection.
```

### Using indexOf() on sparse arrays

You cannot use `indexOf()` to search for empty slots in sparse arrays.

```js
console.log([1, , 3].indexOf(undefined)); // -1
```

### Calling indexOf() on non-array objects

The `indexOf()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`.

```js
const arrayLike = {
  length: 3,
  0: 2,
  1: 3,
  2: 4,
  3: 5, // ignored by indexOf() since length is 3
};
console.log(Array.prototype.indexOf.call(arrayLike, 2));
// 0
console.log(Array.prototype.indexOf.call(arrayLike, 5));
// -1
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.indexof |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Array.prototype.indexOf` in `core-js`
* Indexed collections guide
* `Array`
* `Array.prototype.findIndex()`
* `Array.prototype.findLastIndex()`
* `Array.prototype.lastIndexOf()`
* `TypedArray.prototype.indexOf()`
* `String.prototype.indexOf()`


Array.prototype.with() - JavaScript

Array.prototype.with()
======================

The **`with()`** method of `Array` instances is the copying version of using the bracket notation to change the value of a given index. It returns a new array with the element at the given index replaced with the given value.

Syntax
------

```js
arrayInstance.with(index, value)
```

### Parameters

`index`

Zero-based index at which to change the array, converted to an integer.

* Negative index counts back from the end of the array — if `index < 0`, `index + array.length` is used.
* If the index after normalization is out of bounds, a `RangeError` is thrown.

`value`

Any value to be assigned to the given index.

### Return value

A new array with the element at `index` replaced with `value`.

### Exceptions

`RangeError`

Thrown if `index >= array.length` or `index < -array.length`.

Description
-----------

The `with()` method changes the value of a given index in the array, returning a new array with the element at the given index replaced with the given value. The original array is not modified. This allows you to chain array methods while doing manipulations.

By combining `with()` with `at()`, you can both write and read (respectively) an array using negative indices.

The `with()` method never produces a sparse array. If the source array is sparse, the empty slots will be replaced with `undefined` in the new array.

The `with()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties.

Examples
--------

### Creating a new array with a single element changed

```js
const arr = [1, 2, 3, 4, 5];
console.log(arr.with(2, 6)); // [1, 2, 6, 4, 5]
console.log(arr); // [1, 2, 3, 4, 5]
```

### Chaining array methods

With the `with()` method, you can update a single element in an array and then apply other array methods.

```js
const arr = [1, 2, 3, 4, 5];
console.log(arr.with(2, 6).map((x) => x \*\* 2)); // [1, 4, 36, 16, 25]
```

### Using with() on sparse arrays

The `with()` method always creates a dense array.

```js
const arr = [1, , 3, 4, , 6];
console.log(arr.with(0, 2)); // [2, undefined, 3, 4, undefined, 6]
```

### Calling with() on non-array objects

The `with()` method creates and returns a new array. It reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`. As each property of `this` is accessed, the array element having an index equal to the key of the property is set to the value of the property. Finally, the array value at `index` is set to `value`.

```js
const arrayLike = {
  length: 3,
  unrelated: "foo",
  0: 5,
  2: 4,
  3: 3, // ignored by with() since length is 3
};
console.log(Array.prototype.with.call(arrayLike, 0, 1));
// [ 1, undefined, 4 ]
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.with |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Array.prototype.with` in `core-js`
* Indexed collections guide
* `Array.prototype.toReversed()`
* `Array.prototype.toSorted()`
* `Array.prototype.toSpliced()`
* `Array.prototype.at()`
* `TypedArray.prototype.with()`