Jump to Categories

Array Methods

Methods

sort - sorts the items of array. By default, the sort method sorts the values as strings in alphabetical and ascending order.

var letters = ['D', "B", "A", "C"];

// Array [ "A", "B", "C", "D" ]
console.log(letters.sort());

// Numbers
var nums = [2, 3, 1, 6, 5, 4];

// Array [ 1, 2, 3, 4, 5, 6 ]
console.log(nums.sort(function(a, b){return a-b}))

Iteration methods

Perform a load or wizardry while processing an array. All examples can be found as live code on this codepen.

All of the examples use the following demo array....

var arrPeople = [
  {
    'name': 'Shane',
    'age': 29
  },
  {
    'name': 'James',
    'age': 35
  },
  {
    'name': 'Ro',
    'age': 28
  },
  {
    'name': 'Jordan',
    'age': 21
  },
  {
    'name': 'Luc',
    'age': 18
  }
]

ES6 Syntax

arr.forEach((item) => {
  console.log(item);
});

map - returns an array based on the arguments that you provide inside the map

// Map
var ages = arrPeople.map(function(obj) {
  return obj.age;
});

foreach - loop through all of the array elements

// forEach
arrPeople.forEach(function(obj) {
  //console.log(obj.name)
});

every - returns a boolean - true if every element in this array satisfies the provided testing function

// every
arrPeople.every(function(obj) {
  return obj.age < 25;
});

some - returns a boolean - returns true if the callback function returns true for any array element; otherwise, false.

// some
arrPeople.some(function(obj) {
  console.log(obj);
  return obj.name === 'Shaney';
});

filter - returns an array based on the arguments that were true when looping

// Filter
var filtered = arrPeople.filter(function(obj) {
  return obj.age < 30;
});

reduce - returns a value, takes the prev/next item int he array and can do what want with them in function, useful for summing the contents of array

// Reduce 
arrPeople.reduce(function(a, b) {
  if(a.age < b.age) return a
  else return b
});

reduceRight - as above but starts at end goes backwards

// Reduce right
arrPeople.reduceRight(function(a, b) {
  return b * a;
});

setTimeout inside an array method

fades.forEach((item, index) => {
    setTimeout(function(){
        whatever(item);
    }, 1000 * index);
});

Chaining

// ES6
const combinedLegalAges = arrPeople
  .filter(person => person.age > 17)
  .map(legalPerson => legalPerson.age)
  .reduce((a, b) => a + b);

const combinedLegalAges = arrPeople
  .filter(function (person) {
    return person.age > 17;
  })
  .map(function (legalPerson) {
    return legalPerson.age;
  })
  .reduce(function (a, b) {
    return a + b;
  });

console.log(combinedLegalAges);

Array.prototype.fill()

const a = Array(10).fill(null);

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

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

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