DEV Community

Saurja Ghosh
Saurja Ghosh

Posted on

Array methods in Javascript

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.

Array.of(7); // [7]
Array.of(1, 2, 3); // [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

ii. Array.from()

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

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]
Enter fullscreen mode Exit fullscreen mode

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.

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]
Enter fullscreen mode Exit fullscreen mode

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.

Array.isArray([1, 2, 3]);  // true
Array.isArray({foo: 123}); // false
Array.isArray('foobar');   // false
Array.isArray(undefined);  // false
Enter fullscreen mode Exit fullscreen mode

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.

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

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

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.

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

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

vii. Object.entries()

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

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"
Enter fullscreen mode Exit fullscreen mode

Note: v to vii converts object to array

2. Instance

  1. Push, Pop

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

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

    pop() returns the removed item.

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

    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

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

    shift() returns the removed item.

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

    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.

    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

    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.

    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.

    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.

    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

    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.

    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.

    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.

    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.

    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.

    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.

    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:

    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.

    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.

    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.

    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.

    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.

    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

    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
    

Top comments (0)