Skip to content

Instantly share code, notes, and snippets.

@Lakshay-Batra
Last active September 6, 2020 11:34
Show Gist options
  • Save Lakshay-Batra/c8843dcdd08954a638ea15875ddacb90 to your computer and use it in GitHub Desktop.
Save Lakshay-Batra/c8843dcdd08954a638ea15875ddacb90 to your computer and use it in GitHub Desktop.

Array Methods

  1. toString
    The JavaScript method toString() converts an array to a string of (comma separated) array values.
var names = ["Mike", "Ross", "Tom"];
console.log(names.toString());
// Output: Mike,Ross,Tom
  1. join
    The join() method also joins all array elements into a string, in addition you can specify the separator.
var names = ["Mike", "Ross", "Tom"];
console.log(names.join("-"));
// Output: Mike-Ross-Tom
  1. push
    The push() method adds a new element to an array (at the end), also returns the new array length.
var names = ["Mike", "Ross"];
var length = names.push("Tom");
console.log({ names, length });
// Output: { names: [ 'Mike', 'Ross', 'Tom' ], length: 3 }
  1. pop
    The pop() method removes the last element from an array, also returns the value that was "popped out".
var names = ["Mike", "Ross", 'Tom'];
var name = names.pop();
console.log({ names, name });
// Output: { names: [ 'Mike', 'Ross' ], name: 'Tom' }
  1. shift
    The shift() method removes the first array element and "shifts" all other elements to a lower index, also returns the string that was "shifted out".
var names = ["Mike", "Ross", 'Tom'];
var name = names.shift();
console.log({ names, name });
// Output: { names: [ 'Ross', 'Tom' ], name: 'Mike' }
  1. unshift
    The unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements, also returns the new array length.
var names = ["Ross", 'Tom'];
var length = names.unshift("Mike");
console.log({ names, length });
// Output: { names: [ 'Mike', 'Ross', 'Tom' ], length: 3 }
  1. length
    The length property returns length of array.
var names = ["Mike", "Ross", 'Tom'];
console.log(names.length);
// Output: 3
  1. splice
    The splice() method can be used to add new items to an array and remove some items at the same time. It also returns the array of items that are removed.
var names = ["Mike", "John"];
var _names = names.splice(1, 1, "Ross", "Tom");
// 1st parameter: position where new element should be added.
// 2nd parameter: defines how many elements to be removed.
// Other parameters: elements to be added.
console.log({ names, _names });
// Output: { names: [ 'Mike', 'Ross', 'Tom' ], _names: [ 'John' ] }
  1. concat
    The concat() method creates a new array by merging (concatenating) existing arrays.
    Note: It doesn't change the existing arrays, it always returns a new array.
var namesList1 = ["Mike", "Ross"];
var namesList2 = ["Tom", "John"];
var names = namesList1.concat(namesList2);
console.log(names);
// Output: [ 'Mike', 'Ross', 'Tom', 'John' ]
  1. slice
    The slice() method slices out a piece of an array into a new array.
    Note: It creates a new array. It does not remove any elements from the source array.
var names = ["Mike", "Ross", "Tom", "John"];
var _names = names.slice(1, 3);
// 1st parameter & 2nd parameter: denotes the start and end(but not including).
console.log(_names);
// Output: [ 'Ross', 'Tom' ]
  1. sort
    The sort() method sorts an array alphabetically.
var names = ["Tom", "Mike", "Ross"];
names.sort();
console.log(names);
// Output: [ 'Mike', 'Ross', 'Tom' ]

Numeric sort: to sort numerically

var marks = [40, 50, 30];
marks.sort(function(a, b){return a - b});
console.log(marks);
// Output: [ 30, 40, 50 ]
  1. reverse
    The reverse() method reverses an array.
var names = ["Mike", "Ross", "Tom"];
names.reverse();
console.log(names);
// Output: [ 'Tom', 'Ross', 'Mike' ]
  1. find
    The find() method returns the value of the first element in an array that pass a test (provided as a function).
function search(name) {
    return name == "Ross";
}
var names = ["Mike", "Ross", "Tom"];
console.log(names.find(search));
// Output: Ross
  1. findIndex
    The findIndex() method returns the index of the first element in an array that pass a test (provided as a function).
function search(name) {
    return name == "Ross";
}
var names = ["Mike", "Ross", "Tom"];
console.log(names.findIndex(search));
// Output: 1
  1. copyWithin
    The copyWithin() method copies array elements to another position in the array, overwriting the existing values. This method will never add more items to the array. Note: This method overwrites the original array.
var names = ["Mike", "Ross", "Tom", "John"];
// Syntax: arr.copyWithin(target[, start[, end]])
// 1st parameter: target index where element(s) should be added.
// 2nd parameter (optional): start index of element(s) to be copied.
// If start is omitted, copyWithin will copy from index 0.
// 3rd parameter (optional): end index of element(s) to be copied.
// If end is omitted, copyWithin will copy until the last index (default to arr.length).
names.copyWithin(0, 2, 3); // copy to index 0 the element at index 2
console.log(names);
// Output: [ 'Tom', 'Ross', 'Tom', 'John' ]
  1. entries
    The entries() method returns a new Array Iterator object that contains the key/value pairs for each index in the array.
var names = ["Mike", "Ross", "Tom"];
var _names = names.entries();
console.log(_names.next().value);
console.log(_names.next().value);
// Output: [ 0, 'Mike' ]
//         [ 1, 'Ross' ]

Iterating with index and element

var names = ["Mike", "Ross", "Tom"];
for (const [index, element] of names.entries()) {
    console.log({ index, element });
}
// Output: { index: 0, element: 'Mike' }
//         { index: 1, element: 'Ross' }
//         { index: 2, element: 'Tom' }
  1. every
    The every() method checks if all elements in an array pass a test (provided as a function).
var names = ["Mike", "Ross", "Tom"];
function nameLength(name) {
    return name.length >= 3;
}
console.log(names.every(nameLength));
// Output: true
  1. fill
    The fill() method fills the specified elements in an array with a static value.
var names = ["Mike", "Ross", "Tom"];
names.fill("John");
console.log(names);
// Output: [ 'John', 'John', 'John' ]
  1. flat
    The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
var names = ["Mike", "Ross", ["Tom", "John"]];
console.log(names.flat());
// Output: [ 'Mike', 'Ross', 'Tom', 'John' ]
var names = ["Mike", "Ross", [[["Tom", "John"]]]];
console.log(names.flat(2));
// Output: [ 'Mike', 'Ross', [ 'Tom', 'John' ] ]
  1. includes
    The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.
var names = ["Mike", "Ross", "Tom"];
console.log(names.includes("Ross"));
// Output: true
  1. indexOf
    The indexOf() method searches the array for the specified item, and returns its position and returns -1 if item is not found.
var names = ["Mike", "Ross", "Tom"];
console.log(names.indexOf("Ross"));
// Output: 1
  1. lastIndexOf
    The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex.
var names = ["Mike", "Ross", "Tom", "Ross"];
console.log(names.lastIndexOf("Ross"));
// Output: 3
  1. keys
    The keys() method returns a new Array Iterator object that contains the keys for each index in the array.
var names = ["Mike", , "Tom"];
var keys = names.keys();
for (const key of keys) {
    console.log(key);
}
// Output: 0
//         1
//         2
  1. some
    The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.
var names = ["Mike", "Ross", "Tom"];
function nameLength(name) {
    return name.length > 3;
}
console.log(names.some(nameLength));
// Output: true
  1. toLocaleString
    The toLocaleString() method returns a string representing the elements of the array. The elements are converted to Strings using their toLocaleString methods and these Strings are separated by a locale-specific String (such as a comma “,”).
var names = ["Mike", "Ross", "Tom", new Date(' 28 Aug 2020 14:30:00 UTC')];
const localeString = names.toLocaleString('en', { timeZone: "Asia/Kolkata" });
console.log(localeString);
// Output: Mike,Ross,Tom,8/28/2020, 8:00:00 PM
  1. forEach
    The forEach() method executes a provided function once for each array element.
var names = ["Mike", "Ross", "Tom"];
names.forEach(name => console.log(name.length));
// Output: 4
//         4
//         3
  1. map
    The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
var names = ["Mike", "Ross", "Tom"];
var lengths = names.map(name => name.length);
console.log(lengths);
// Output: [ 4, 4, 3 ]
  1. flatMap
    The flatMap() method first maps each element using a mapping function, then flattens the result into a new array. It is identical to a map() followed by a flat() of depth 1.
var names = ["Mike", "Ross", "Tom"];
var namesAndLengths = names.flatMap(name => [name, name.length]);
console.log(namesAndLengths);
// Output: [ 'Mike', 4, 'Ross', 4, 'Tom', 3 ]
  1. filter
    The filter() method creates a new array with all elements that pass the test implemented by the provided function.
var names = ["Mike", "Ross", "Tom"];
var filteredNames = names.filter(name => {
    return name.length > 3;
});
console.log(filteredNames);
// Output: [ 'Mike', 'Ross' ]
  1. reduce
    The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.
var names = ["Mike", "Ross", "Tom"];
var concatNames = names.reduce((acc, cur) => {
    return acc + cur;
});
console.log(concatNames, "");
// Output: MikeRossTom
  1. reduceRight
    The reduceRight() method applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value.
var names = ["Mike", "Ross", "Tom"];
var concatNames = names.reduceRight((acc, cur) => {
    return acc + cur;
});
console.log(concatNames, "");
// Output: TomRossMike
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment