How to replicate this for-loop using forEach()?

Viewed 79

How would one replicate this for-loop using 'Array.prototype.forEach() ' ?

const getSums = (arr) => {
  let result = []
  for (let i = 0; i < arr.length - 1; i++) {
    result.push(arr[i] - arr[i + 1])
  }
  return result
}

console.log(getSums([100, 99, 99, 100]))

expected output: [1, 0, -1]

5 Answers

forEach can give you an index of element. You could use that.

const getSums = (arr) => {
    let result = []
    arr.forEach((el, i) => {
        if (i < arr.length - 1) result.push(el - arr[i + 1])
    })
    return result
}
console.log(getSums([100, 99, 99, 100]))

A pure FP solution is somewhat bulky, because JS doesn't have built-in zip, but here you go

let zip = (a, b) => a.map((_, i) => [a[i], b[i]])

a = [100, 99, 99, 100]

deltas = zip(a.slice(0, -1), a.slice(1)).map(([x, y]) => x - y)

console.log(deltas)

It's like an Array.forEach, with a some addintions : array.reduce() method
like initialize your array

const getSums = arr => arr.reduce((result,current,i,{[i+1]:next}) =>
  {                                               //       next = arr[i+1]
  if (!isNaN(next))             // if next is not a number 
    result.push(current -next); // !isNaN(undefined) == false
  return result
  }
  , []) // initialize -> result=[]
  
console.log('getSums',JSON.stringify(getSums([100, 99, 99, 100])))


//OneLine Code:
const deltas =A=>A.reduce((r,c,i,{[i+1]:n})=>(!isNaN(n)?r[i]=c-n:'',r),[])

console.log('deltas', JSON.stringify(deltas([100, 99, 99, 100])))

it is preferable to use an isNaN() to test the presence of the value of next, rather than a simple if(next), because this test would be falsified if next had a value of zero.

Instead of using the index, you could save the previous value outside of the loop.

const getSums = (arr) => {
    let result = []
    let prev = null;
    arr.forEach(el => {
        if (prev) {
          result.push(prev - el);
        }
        prev = el;
    })
    return result
}
console.log(getSums([100, 99, 99, 100]))

With using forEach loop, you can have each element's value and indexes.

So, making this calculations, need to take element at index and element at index+1. We pushed each answers inside of an empty array.

At the end of arr's index, there's no element at element[index+1]. Because index is already eqaual with arr.length. Therefore, we added (arr.length != index+1) condition too.

This condition gives you to check and block the error can happen from couldn't find element of array.

const result = []
    arr.length > 0 && arr.forEach((element, index)=> {
          arr.length != index+1 && result.push(element - element[index+1))
        })
Related