Skip to content

Instantly share code, notes, and snippets.

@askingalot
Last active November 30, 2020 20:57
Show Gist options
  • Save askingalot/122ff0f8e552a0c894257649239c8ff8 to your computer and use it in GitHub Desktop.
Save askingalot/122ff0f8e552a0c894257649239c8ff8 to your computer and use it in GitHub Desktop.
My Array Functions

My Array Functions

A JavaScript Exercise

JavaScript arrays are a powerful tool for building complex applications. Along with the ability to store sequential data, the good people at TC39 have given us many useful array methods to make our lives easier. There are methods for modifying, looping over, transforming, sorting, querying and filtering arrays.

While array methods make it a LOT easier to use arrays, most of the things array methods do could be done with more low level JavaScript code. For example, if you wanted to write a function that did the same things as the array filter method, you might write something like this.

function myFilter(array, condition) {
  const result = [];
  for (let i = 0; i < array.length; i++) {
    const element = array[i];
    if (condition(element, i, array)) {
      result.push(element);
    }
  }
  return result;
}

And you could use it like this

const myArray = [100, 1, 200, 2, 300, 3];
const filtered = myFilter(myArray, (num) => num < 100);

console.log(filtered);
// [1, 2, 3]

The Exercise

Write your own "myXXX" functions to mimic the behavior of the following array methods.

  • forEach()
  • map()
  • includes()
  • some()
  • every()
  • find()
  • indexOf()
  • lastIndexOf()
  • join()
  • concat()
  • reduce()
  • reverse()

NOTES:
You may use the push() array method, but do not use any other methods in your functions.
But you may use prevously written myXXX functions.
See this link for a description of what the methods do.

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