DEV Community

Ruxin Qu
Ruxin Qu

Posted on • Edited on

JavaScript: Array

  • create an array:let arrayName = ['item1','item2','item3'];
  • array.length shows the number of items in the array.

  • array.push('item4','item5') can add items to the array at the end.

  • array.pop() doesn't contain arguments, deletes the last item in the array.

  • array.shift() removes the first item in the array.
    array.unshift('item0') adds item to the beginning of the array.

  • array.join() can connect array elements with ,;

array.join(''): no space between each element;

array.join('-') connects each element with -.

  • array.slice(begin, end(optional)) is non-mutating.

For example:

array = [1,2,3,4,5,6];
console.log(array.slice(2));   //output: [3, 4, 5, 6]
console.log(array.slice(2,4));  //output: [3, 4]
console.log(array);  //output: [1,2,3,4,5,6]
Enter fullscreen mode Exit fullscreen mode
  • array.indexOf('item2') returns the index of the element.
  • let arrays are mutable and can be reassigned;

const arrays are mutable but can't be reassigned.

For example:

let arrayOne = [1,2,3,4,5]
arrayOne[2] = 8;
console.log(arrayOne);   //output: [1, 2, 8, 4, 5]
arrayOne = ['This','is','a','new','array'];
console.log(arrayOne);   //output: ["This", "is", "a", "new", "array"]
Enter fullscreen mode Exit fullscreen mode
const arrayTwo = [1,2,3,4,5]
arrayOne[2] = 8;
console.log(arrayTwo);   //output: [1, 2, 8, 4, 5]
arrayTwo = ['This','is','a','new','array'];   //output: TypeError: Attempted to assign to readonly property.
Enter fullscreen mode Exit fullscreen mode
  • .forEach() goes through all the elements in an array and return undefined. (no return inside the function body)
  • .map() executes the same action on every element in an array and return a new array.
  • .filter() checks every element in an array and returns those meet the criteria.
  • .findIndex() returns the index of the first element in the array that meets the condition.
  • .every() will return a boolean value.
  • .reduce() can go through the array and return one value.

For example:

const numbers = [1,2,3,4,5,6];
const sum = numbers.reduce((accumulator, currentValue)=>{
  return accumulator + currentValue;
});
console.log(sum);    //output: 21 
Enter fullscreen mode Exit fullscreen mode
  • .split(' ') will separate the string by the ' ', and store each word as an element in an array. The variable takes those arrays become an object.
  • To test if an object is an array or not, use Array.isArray(objectName).
  • Array.sort((x,y)=>y-x) or array.reverse(array.sort()) returns the array in descending order
  • Array.includes() returns whether an array includes a certain value among its entries; string.match() returns the result of a string matching a specific expression.

Top comments (0)