kaniosrn-j
2/18/2018 - 3:57 PM

Common Use Array Methods

var arr = ['a', 'b', 'c'];

  // push() - Add a new element into an array
  arr.push('d');

  // pop() - remove the last element of an array and return that element
  arr.pop();

  // concat() - concatenates to an array. This will not affect the original array
  var newArr = ['e']
  arr.concat(newArr);

  // join() - This joins all the elements in an array to create a string and also will no modify the original Array
  arr.join();

  // reverse() - this reverses the elements in an . This will change the original array
  arr.reverse();

  // shift() - this will remove the first element in the array and return that element. This wiil change the original array
  arr.shift();

  // unshift('newArray') - add element to the begining of your array and return the length of the modified array
  arr.unshift('newArr');

  // slice() - this will select part of an array and return that new array you selected and the original array remain UNCHANGED
  arr.slice(startAtIndexOne, endMinusOne);

  // sort() - sort an array. this will change the original array
  arr.sort();

  // splice() - this is similar to slice(), but it will modify the original array instead of just returning new array.
  // array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
  var months = ['Jan', 'March', 'April', 'June'];
  months.splice(1, 0, 'Feb');
  // inserts at 1st index position
  console.log(months);
  // expected output: Array ['Jan', 'Feb', 'March', 'April', 'June']

  months.splice(4, 1, 'May');
  // replaces 1 element at 4th index
  console.log(months);
  // expected output: Array ['Jan', 'Feb', 'March', 'April', 'May']
</script>