Javascript array functions

Brought to you by

Who is this for?

  • Devs new to javascript
    • But who do understand arrow functions, destructuring (as those will be used in examples)

History

&

Browser support

ECMA Script 5 (2009)

  • Array.isArray()
  • Array.forEach()
  • Array.map()
  • Array.filter()
  • Array.reduce()
  • Array.reduceRight()
  • Array.every()
  • Array.some()
  • Array.indexOf()
  • Array.lastIndexOf()

ECMA Script 5 (2009)

  • Array.isArray()
  • Array.forEach()
  • Array.map()
  • Array.filter()
  • Array.reduce()
  • Array.reduceRight()
  • Array.every()
  • Array.some()
  • Array.indexOf()
  • Array.lastIndexOf()

ECMA Script 5 (2009)

ECMA Script 6 (2015)

  • Array.find()
  • Array.findIndex()

.forEach()

.forEach()

  • What it's for: Looping through every element in an array
  • Returns: undefined
  • "Executes a provided function once for each array element."
  • Easy to understand
  • Not super useful

.forEach()

const myArray = [
    { id: 234, name: 'John Snow' },
    { id: 542, name: 'Daenerys Targaryen' },
    { id: 756, name: 'Arya Stark' },
];

myArray.forEach((element, index) => {
    console.log(index, ': ', element.name);
});
0: John Snow
1: Daenerys Targaryen
2: Arya Stark
const myArray = [
    { id: 234, name: 'John Snow' },
    { id: 542, name: 'Daenerys Targaryen' },
    { id: 756, name: 'Arya Stark' },
];

myArray.forEach(({ name }, index) => {
    console.log(index, ': ', name);
});

.forEach()

const myArray = [
    { id: 234, name: 'John Snow' },
    { id: 542, name: 'Daenerys Targaryen' },
    { id: 756, name: 'Arya Stark' },
];


const anotherArray = [];

myArray.forEach(({ name }) => {
    anotherArray.push(name);
});

return anotherArray;

You may be tempted to....

.forEach()

const foundElement = {}

myArray.forEach((element) => {
    if (element.id === 234) {
        foundElement = element;
    }
});

return foundElement;

You may be tempted to....

.find()

.find()

  • What it's for: Finding one element in an array that meets certain conditions
  • Returns: one array element (or undefined)
  • "returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned."
  • Also easy to understand
  • Usually one line
  • Super useful

.find()

const myArray = [
    { id: 234, name: 'John Snow' },
    { id: 542, name: 'Daenerys Targaryen' },
    { id: 756, name: 'Arya Stark' },
];

const john = myArray.find(({ name }) => name === 'John Snow');

console.log(john);
{ name: 'John Snow', id: 234 }

.find()

const myArray = [
    { id: 234, name: 'John Snow' },
    { id: 542, name: 'Daenerys Targaryen' },
    { id: 756, name: 'Arya Stark' },
];

const exists = myArray.find(({ name }) => name === 'John Snow');

if (exists) {
    // do stuff
}

You may be tempted to....

.some()

.some()

  • What it's for: seeing if an element exists in an array
  • Returns: boolean
  • "Tests whether at least one element in the array passes the test implemented by the provided function."
  • Semantic correctness FTW
  • Somewhat useful

.some()

const myArray = [
    { id: 234, name: 'John Snow' },
    { id: 542, name: 'Daenerys Targaryen' },
    { id: 756, name: 'Arya Stark' },
];

const exists = myArray.some(({ name }) => name.endsWith('Stark'));

console.log(exists);
true

.endsWith support:

(ES6)

.filter()

.filter()

  • What it's for: filtering out some elements in an array
  • Returns: new array of elements
  • "Creates a new array with all elements that pass the test implemented by the provided function."
  • SUPER useful

.filter()

[
    { id: 542, name: 'Tony Stark' },
    { id: 756, name: 'Arya Stark' }
]
const myArray = [
    { id: 234, name: 'John Snow' },
    { id: 542, name: 'Tony Stark' },
    { id: 756, name: 'Arya Stark' },
];

const starks = myArray.filter(({ name }) => {
    return name.endsWith('Stark');
});

console.log(starks);

.map()

.map()

  • What it's for: changing elements in an array to look like a different array
  • Returns: new array of elements
  • "Creates a new array with the results of calling a provided function on every element in the calling array."
  • A little hard to understand
  • Very useful

.map()

const myArray = [
    { id: 234, name: 'John Snow' },
    { id: 542, name: 'Daenerys Targaryen' },
    { id: 756, name: 'Arya Stark' },
];

const names = myArray.map(({ name }) => name);

console.log(names);
[
    'John Snow',
    'Daenerys Targaryen',
    'Arya Stark',
]

.map()

const myArray = [
    { id: 234, name: 'John Snow' },
    { id: 542, name: 'Daenerys Targaryen' },
    { id: 756, name: 'Arya Stark' },
];

const names = myArray.map(({ name }) => {
    const n = name.split(' ');

    return { 
        firstName: n[0],
        lastName: n[1],
    };
});

console.log(names);
[
    { firstName: 'John', lastName: 'Snow' },
    { firstName: 'Daenerys', lastName: 'Targaryen' },
    { firstName: 'Arya', lastName: 'Stark' },
]

.map()

const myArray = [
    { id: 234, name: 'John Snow' },
    { id: 542, name: 'Tony Stark' },
    { id: 756, name: 'Arya Stark' },
];

const starkNames = myArray
    .filter(({ name }) => name.endsWith('Stark')
    .map(({ name } => name);

You may be tempted to....

.reduce()

.reduce()

  • What it's for: filtering and mapping, adding values
  • Returns: whatever you want
  • "Executes a reducer function (that you provide) on each member of the array resulting in a single output value."
  • Hard to understand
  • Powerful
  • Somewhat useful

.reduce()

const myArray = [
    { id: 234, amount: 1 },
    { id: 542, amount: 4 },
    { id: 756, amount: 6 },
];

const total = myArray.reduce((result, { amount }) => {
    result += amount;

    return result;
}, 0);

console.log(total);
11

.reduce()

const myArray = [
    { id: 234, name: 'John Snow' },
    { id: 542, name: 'Tony Stark' },
    { id: 756, name: 'Arya Stark' },
];

const starks = myArray.reduce((result, { name }) => {
    if (name.endsWith('Stark')) {
        const n = names.split(' ');
        result.push({ firstName: n[0], lastName: n[1] });
    }

    return result;
}, []);

console.log(starks);
[
    { firstName: 'Tony', lastName: 'Stark' },
    { firstName: 'Arya', lastName: 'Stark' }
]

.reduce() (map + filter)

const myArray = [
    { id: 234, name: 'John Snow' },
    { id: 542, name: 'Tony Stark' },
    { id: 756, name: 'Arya Stark' },
];

const starks = myArray.filter(({ name }) => name.endsWith('Stark'))
               .map(({ name }) => {
                   const n = name.split(' ');
                   return { firstName: n[0], lastName: n[1] };
               });

console.log(starks);
[
    { firstName: 'Tony', lastName: 'Stark' },
    { firstName: 'Arya', lastName: 'Stark' }
]

Examples

Situation

Function to use

See if an array of payments contains a payment over $100

.some()

Display the results of a search

.filter()

Add up the total amount paid from an array of payments

.reduce()

Display all payments over $100

.filter()

From a list of synced accounts, get the user's Gmail account

.find()

Situation

Function to use

Display dates in an array in moment format rather than system time

.map()

Send only the ids of a list of contacts to the backend 

.map()

Display only late invoices

.filter()

Display only contacts added in the last week

.filter()

Display whether or not there were contacts added in the last week

.some()

Javascript array functions

By Laurel Bruggeman

Javascript array functions

  • 549