Skip to content

Instantly share code, notes, and snippets.

@somahargitai
Last active May 8, 2024 13:20
Show Gist options
  • Save somahargitai/c4c873bdbca0e2ee618789d01ca0a9d2 to your computer and use it in GitHub Desktop.
Save somahargitai/c4c873bdbca0e2ee618789d01ca0a9d2 to your computer and use it in GitHub Desktop.
Array Processing functions in ES6 Javascript

cheatsheet list

Array Processing functions in ES6 Javascript

copy array

shallow copy

Create a copy. Modifications on the object will modify the original one too.

const shallowcopyclone = {...myobject};

deep copy

Create an independent copy. Modifications on the object will NOT modify the original one.

const deepcopyclone = JSON.parse(JSON.stringify(myobject));

modify array

slice

const array2 = array1.slice() simply creates a shallow copy. With parameters like slice(1,3) you can get parts of the array. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

finding information, creating a new set of data

.forEach(), .map(), .reduce(), .filter(), find(), every(), some()

forEach

map

reduce

Here we select odd numbers and add them to our list.

const nums = [79, 48, 12, 4, 48, 33];

const startArray = [3, 7];
const reduceResult = nums.reduce((acc, item, index, source) => {
  console.log('new loop turn');
  console.log(`acc: ${acc}`);
  console.log(`item: ${item}`);
  console.log(`index: ${index}`);
  console.log(`source: ${source}`);
  if(item % 2) acc.push(item);
  return acc;

}, startArray);

console.log(startArray);
console.log(nums);
console.log(reduceResult);

filter

find

! pretty often the best way to find is to use some or every

find if element exists in array. Returns first array item fulfilling conditions, undefined if not item found.

const findNums = [79, 48, 12, 4, 48, 33];

const findIt1 = findNums.find(item => item === 12);
console.log('findIt 1 - ', findIt1);

const findIt2 = findNums.find(item => item === 8);
console.log('findIt 2 - ', findIt2);

const findObjectArray = [
  { name: 'jack', fullName: 'flap jack', data: [1, 2, 3, 4, 5, 6]},
  { name: 'john', fullName: 'john does', data: [1, 2, 3, 4, 5, 6]},
  { name: 'jack', fullName: 'bad jack', data: [1, 2, 3, 4, 5, 6]},
  { name: 'mary', fullName: 'mary blood', data: [1, 2, 3, 4, 5, 6]},
]

const findIt3 = findObjectArray.find(item => item.name === 'jack');
console.log('findIt3 - ', findIt3);

every

check if all the list elements contain hours and seconds (find if there is an invalid item)

  const timeList = [
    '11:23`,
    '13:23`,
    '08:59`,
    '99:99`,
    null,
    undefined,
  ];
  const regexMatch = /^(?:[01]\d|2[0-3]):[0-5]\d$/;
  const isEveryValid = timeList.every((time) =>
    time !== null
    && time !== undefined
    && time.length === 5
    && time.match(regexMatch));

some

sort

const nums = [79, 48, 12, 4];

function compare(a, b) {
  if (a > b) return 1;
  if (b > a) return -1;

  return 0;
}

nums.sort(compare);
// => 4, 12, 48, 79

It is the same, just logs the algorithm:

const nums = [79, 48, 12, 4, 48, 33];

function compare(a, b) {
  if (a > b) {
    console.log(`a=${a} is greater than b=${b}`)
    return 1;
  }
  if (b > a) {
    console.log(`a=${a} is fewer than b=${b}`)
    return -1;
  }

  console.log(`a=${a} equals b=${b}`)
  return 0;
}

nums.sort(compare);
console.log(nums);

ES6

const nums = [79, 48, 12, 4, 48, 33];

nums.sort((a,b) => {
  if (a > b) return 1;
  if (b > a) return -1;
  return 0;
});

console.log(nums);

Typical example: date sorting with moment.js's .diff() function:

const sortedArray = array.sort((a, b) => a.diff(b))

Array processing functions in ES6 Javascript

.forEach(), .map(), .reduce(), .filter(), find(), every(), some()

🦀 Each receives a callback function as a parameter.

🐬 You can always replace explicit callback functions with fat arrow functions. If it is handy, you can replace the function body with the return value to make the code tinier. So these are the same callback functions:

  • function (ageParam) { return ( { name: 'jack', age: ageParam }) }
  • (ageParam) => { return ( { name: 'jack', age: ageParam }) }
  • ageParam => ({ name: 'jack', age: ageParam }) ---> I had to put parentheses, so it is an object, not a code block

Use for what

  • Reduce is for general array processing. It can result any type of value: object, array, string, number. This is the only one we use with two parameters. First parameters is the Callback Function, second is the Starting Value. The callback function can use four parameters: accumulator, item, item index and the original starting value.
  • The every() and some() return true or false and the callback function should also return true or false . These are to check if some or every array items fulfils a condition.
  • The find() excepts a callback function to return true or false and returns the first true item. If there can be multiple fitting items, use filter() instead! .map() is to create an array from an array, with the same size.

Typical examples

const people = [
    { _id: "person_1", name: "Steve Jobs",      age: 56, isAlive: false, likeHim: false},
    { _id: "person_2", name: "Elon Musk",       age: 49, isAlive: true,  likeHim: false},
    { _id: "person_3", name: "Bob Ross",        age: 52, isAlive: false, likeHim: true},
    { _id: "person_4", name: "Mark Zuckerberg", age: 36, isAlive: true,  likeHim: false}
];
const hellos = ['hello', 'hi', 'hey', 'yo', 'hiya', 'howdy'];

Simple operations

const fiveYearsLater = people.map(person => {
    return {
        ...person,
        age: person.age + 5
    }
});
const names = people.map(person => person.name);
const thePersonILike = people.find(person => person.likeHim);
const onePersonIDontLike = people.find(person => !person.likeHim); // we only get the first!
const peopleIDontLike = people.filter(person => !person.likeHim); // we get all of them
const peopleAlive = people.filter(person => person.isAlive);
const isAnyoneAlive = people.some(person => { return person.isAlive } );
const areAllPeopleAlive = people.every(person => person.isAlive);

Complex operations with reduce

// returns a number
const averageAge = ( people.reduce((acc, person) => acc + person.age, 0) ) / people.length; 
// returns an object, found in the array
const oldestPerson = people.reduce((oldest, person) => {
    return (oldest.age > person.age) ? oldest : person;
}); 
// returns a string, assembled by using the array
const sayHelloForEveryBody = people.reduce((acc, person, personIndex, original) => {
    const isLastPerson = personIndex === original.length - 1;
    return `${acc}${hellos[Math.floor(Math.random() * hellos.length)]} ${person.name}${isLastPerson ? '!' : ', '}`;
}, ''); 
// return an object which has different properties
const apocalypseEstimation = people.reduce(
    (acc, person) => {
        const { age, isAlive } = person;
        if (isAlive) {
            acc.alive++;
            acc.totalAge += age;
        } else {
            acc.dead++;
        }
        return acc;
    },
    { alive: 0, dead: 0, totalAge: 0 }
);
// start value is a non-empty array and extract information into it
const peopleOfMyBand = people.reduce((acc, person) => {
    if (person.likeHim || person.isAlive) {
        acc.push({ fullName: person.name, hobby: 'music' });
    }
    return acc; // I have to return the accumulator!
},[
    { fullName: 'Jack Black',   hobby: 'guitar' },
    { fullName: 'Phil Collins', hobby: 'drums' },
]);

Other array functions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment