Some important array methods and their polyfills

Arrays are one of the most important data structure in any programming language. It is basically a collection of elements or items. Array store data as element and retrieve them back when needed.

In this blog we will understand some important array methods in JavaScript and dive into deep to understand how they work. (Also we will write them from scratch)

What is method ?

JavaScript methods are actions that can be performed on arrays / objects. method is a property containing a function definition.

Lets now look at these methods one by one

forEach

forEach method calls a function for each element of array. return value is undefined in this case.

let arr = [1,2,3]
arr.forEach(item=>console.log(item))
// output will be 
// 1
// 2
// 3

pretty simple right! Lets look at how we can write our own version this.

forEach polyfill

function forEachPolyfill(array, cb) {
  for (let i = 0; i < array.length; i++) {
    cb(array[i], i, array)
  }
}

This will work exactly as the inbuilt method.

map

map is one of the most important and most used methods in array. it returns a new array with applied function on each elements.

const array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1); // [2,8,18,32]

Here map1 will have new array in which every element of it will be the result of callback function.

map polyfill

function mapPolyfill(array, cb) {
  const newArray = []
  for (let i = 0; i < array.length; i++) {
    newArray.push(cb(array[i], i, array))
  }

  return newArray
}

here in this polyfill we are iterating through the previous array and then pushing the result of callback function into the new array.

filter

As the name indicates, filter helps to filter out the contents of array. it returns a new array with those elements who have passed the given test.

const words = ['Akshay', 'Akanksha', 'Tanay', 'Kavya'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["Akanksha"]

The only one word passed our test , hence new array consists of only one word.

filter polyfill

function filterPolyfill(array, cb) {
  const newArray = []
  for (let i = 0; i < array.length; i++) {
    const element = array[i]
    if (cb(element, i, array)) newArray.push(element)
  }

  return newArray
}

Here we are taking one element and passing to callback function and if that passes the test then it is being pushed to new array.

reduce

This one of the notorious methods out there but also very useful. As name suggests it helps to reduce your array in one value (that value can be number, array or object). it returns value that results from running the "reducer" callback function to completion over the entire array.

const array1 = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (previousValue, currentValue) => previousValue + currentValue,
  initialValue
);

console.log(sumWithInitial);
// expected output: 10

unlike other methods this little bit tricky to understand. It takes callback function but that two parameters, one is previousValue and other is currentValue . At the first iteration the previousValue is set to the initialValue and currentValue is the first element of array. The result of this operation becomes the previousValue for the next iteration and so on it continues. finally at the end of the array we receive our results.

reduce polyfill

function reducePolyfill(array, cb, initialValue) {
  let previousValue = initialValue
  for (let i = 0; i < array.length; i++) {
    const currentValue = array[i]
    if (initialValue == null && i === 0) {
      previousValue = currentValue
    } else {
      previousValue = cb(previousValue, currentValue, i, array)
    }
  }

  return previousValue
}

As explained above this is how reduce works internally and previousValue will be returned in the end.

some

This method is very straightforward. some tests whether at least one element passes the test implemented by callback function. it returns true if it finds such element otherwise it returns false.

const array = [1, 2, 3, 4, 5];

// checks whether an element is even
const even = (element) => element / 2 === 0;

console.log(array.some(even));
// expected output: true

some polyfill

function some(array, cb) {
  for (let i = 0; i < array.length; i++) {
    if (cb(array[i], i, array)) return true
  }

  return false
}

if our element in the array are fulfilling the condition then we are returning true otherwise we are returning false. Pretty simple right!

find

As name suggests, it helps to find specific element in array. it returns the first element in the provided array that satisfies the provided callback function.

const array1 = [5, 12, 8, 130, 44];

const found = array1.find(element => element > 10);

console.log(found);
// expected output: 12

Here there are multiple numbers greater than 10 but the first occurrence is of ‘12’ that's why it returned 12. (so use it to find unique things)

find polyfill

function find(array, cb) {
  for (let i = 0; i < array.length; i++) {
    const element = array[i]
    if (cb(element, i, array)) return element
  }
}

like all the methods we discussed loop over the array and then if our element satisfies the callback functions condition then we return that

Conclusion

So here are some of the important array methods with their polyfills. Polyfills are also important to understand because they are used to provide modern functionality on older browsers that do not natively support it. I hope this content helped you!