Array methods in Javascript
Tags: webdev, javascript, javascriptarraymethods, cheatsheet
Published: 2021-09-11 02:16:40

## 1. Static

### i. Array.of()

The Array.of() method creates a new Array instance from a variable number of arguments, regardless of number or type of the arguments.

```tsx
Array.of(7); // [7]
Array.of(1, 2, 3); // [1, 2, 3]
```

### ii. Array.from()

The Array.from() static method creates a new, shallow-copied Array instance from an array-like or iterable object.

```tsx
console.log(Array.from('foo')); // expected output: Array ["f", "o", "o"]
console.log(Array.from([1, 2, 3], x => x + x)); // expected output: Array [2, 4, 6]
```

### iii. Array.fill()

The fill() method changes all elements in an array to a static value, from a start index (default 0) to an end index (default array.length). It returns the modified array.

```tsx
const array1 = [1, 2, 3, 4];

// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// expected output: [1, 2, 0, 0]

// fill with 5 from position 1
console.log(array1.fill(5, 1));
// expected output: [1, 5, 5, 5]

console.log(array1.fill(6));
// expected output: [6, 6, 6, 6]
```

Note: From i to iii the methods returns a new array

### iv. Array.isArray()

The Array.isArray() method determines whether the passed value is an Array.

```tsx
Array.isArray([1, 2, 3]);  // true
Array.isArray({foo: 123}); // false
Array.isArray('foobar');   // false
Array.isArray(undefined);  // false
```

### v. Object.keys()

The Object.keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.

```tsx
const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};

console.log(Object.keys(object1));
// expected output: Array ["a", "b", "c"]
```

### vi. Object.values()

The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop.

```tsx
const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};

console.log(Object.values(object1));
// expected output: Array ["somestring", 42, false
```

### vii. Object.entries()

The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs.

```tsx
const object1 = {
  a: 'somestring',
  b: 42
};
console.log(Object.entries(object1)) //[["a","somestring"],["b",42]]
for (const [key, value] of Object.entries(object1)) {
  console.log(`${key}: ${value}`);
}
// expected output:
// "a: somestring"
// "b: 42"
```

Note: v to vii converts object to array

## 2. Instance

1. Push, Pop

    **pop()**: Remove an item from the end of an array

    ```tsx
    let cats = ['Bob', 'Willy', 'Mini'];
    cats.pop(); // ['Bob', 'Willy']
    ```

    pop() returns the removed item.

    **push()**: Add items to the end of an array

    ```tsx
    let cats = ['Bob'];
    cats.push('Willy'); // ['Bob', 'Willy']
    cats.push('Puff', 'George'); // ['Bob', 'Willy', 'Puff', 'George']
    ```

    push() returns the new array length.

2. shift, unshift

    **shift()**: Remove an item from the beginning of an array

    ```tsx
    let cats = ['Bob', 'Willy', 'Mini'];
    cats.shift(); // ['Willy', 'Mini']
    ```

    shift() returns the removed item.

    **unshift()**: Add items to the beginning of an array

    ```tsx
    let cats = ['Bob'];
    cats.unshift('Willy'); // ['Willy', 'Bob']
    cats.unshift('Puff', 'George'); // ['Puff', 'George', 'Willy', 'Bob']
    ```

    *unshift()* returns the new array length.

3. join, split

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

    The split() method splits a String object into an array of strings by separating the string into substrings.

    ```tsx
    var a = "asdasd|dasd|rttewrtert";
    var b = a.split('|');
    // ["asdasd", "dasd", "rttewrtert"]
    var d = c.join('');
    // asdasddasdrttewrtert
    ```

4. slice, splice

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

    ```tsx
    const months = ['Jan', 'March', 'April', 'June'];
    months.splice(1, 0, 'Feb');
    // inserts at index 1
    console.log(months); // expected output: Array ["Jan", "Feb", "March", "April", "June"]
    ```

    The slice() method 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.

    ```tsx
    const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
    console.log(animals.slice(2, 4));
    // expected output: Array ["camel", "duck"]
    console.log(animals.slice(2, -1));
    // expected output: Array ["camel", "duck"]
    ```

5. indexof, lastindexof

    The lastIndexOf() method returns the position of the last occurrence of a specified value in a string, where as indexOf() returns the position of the first occurrence of a specified value in a string.

    ```tsx
    var str = "Hello planet earth, you are a great planet.";
    var n = str.lastIndexOf("planet");
    var n2 = str.indexOf("planet");
    // n will return 36 and n2 will return 6
    ```

6. includes

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

    ```tsx
    const array1 = [1, 2, 3];
    console.log(array1.includes(2)); // expected output: true
    const pets = ['cat', 'dog', 'bat'];
    console.log(pets.includes('cat')); // expected output: true
    console.log(pets.includes('at')); // expected output: false
    ```

7. reverse

    ```tsx
    const array1 = ['one', 'two', 'three'];
    console.log('array1:', array1);
    const reversed = array1.reverse();
    console.log('reversed:', reversed);
    // expected output: "reversed:" Array ["three", "two", "one"]
    ```

    ! Careful: reverse is destructive -- it changes the original array.

    ```tsx
    console.log('array1:', array1);
    // expected output: "array1:" Array ["three", "two", "one"]
    ```

## 3. Callback

1. Filter

    The filter() method creates a new array with all elements that pass the test implemented by the provided function.

    ```tsx
    const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
    const result = words.filter(word => word.length > 6);
    console.log(result); 
    // expected output: Array ["exuberant", "destruction", "present"]
    ```

2. Find

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

    ```tsx
    const array1 = [5, 12, 8, 130, 44];
    const found = array1.find(element => element > 10);
    console.log(found); // expected output: 12
    ```

3. every

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

    ```tsx
    const isBelowThreshold = (currentValue) => currentValue < 40;
    const array1 = [1, 30, 39, 29, 10, 13];
    console.log(array1.every(isBelowThreshold));
    // expected output: true
    ```

4. Sort

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

    ```tsx
    const months = ['March', 'Jan', 'Feb', 'Dec'];
    months.sort();
    console.log(months);
    // expected output: Array ["Dec", "Feb", "Jan", "March"]
    ```

    Arrays would be sorated as strings by default.

    ```tsx
    const array1 = [1, 30, 4, 21, 100000];
    array1.sort();
    console.log(array1);
    // expected output: Array [1, 100000, 21, 30, 4]
    ```

    A contrived approach to sort numbers, without using a comparator function, is to make use of a typed array:

    ```tsx
    const numbers = [10, 5, 11];
    const sortedNumbers = [...new Float64Array(numbers).sort()];
    sortedNumbers; // => [5, 10, 11]
    ```

5. Some

    The some() method 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.

    ```tsx
    const array = [1, 2, 3, 4, 5];
    // checks whether an element is even
    const even = (element) => element % 2 === 0;

    console.log(array.some(even)); // expected output: true
    ```

## 4. Looping

1. foreach

    The forEach() method executes a provided function once for each array element.

    ```tsx
    const array1 = ['a', 'b', 'c'];
    array1.forEach(element => console.log(element));
    // expected output: "a"
    // expected output: "b"
    // expected output: "c"
    ```

2. filter

    The filter() method creates a new array with all elements that pass the test implemented by the provided function.

    ```tsx
    const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
    const result = words.filter(word => word.length > 6);
    console.log(result);
    // expected output: Array ["exuberant", "destruction", "present"]
    ```

3. map

    The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

    ```tsx
    const array1 = [1, 4, 9, 16];
    // pass a function to map
    const map1 = array1.map(x => x * 2);
    console.log(map1);
    // expected output: Array [2, 8, 18, 32]
    ```

4. reduce [ A loop with a memory ]

    The reduce() method executes a user-supplied “reducer” callback function on each element of the array, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

    ```tsx
    const array1 = [1, 2, 3, 4];
    const reducer = (accumulator, currentValue) => accumulator + currentValue;

    // 1 + 2 + 3 + 4
    console.log(array1.reduce(reducer));
    // expected output: 10

    // 5 + 1 + 2 + 3 + 4
    console.log(array1.reduce(reducer, 5));
    // expected output: 15
    ```

    We can also use reduce method for objects

    ```tsx
    let initialValue = 0
    let sum = [{x: 1}, {x: 2}, {x: 3}].reduce(function (previousValue, currentValue) {
        return previousValue + currentValue.x
    }, initialValue)

    console.log(sum) // logs 6
    ```