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

Time:09-10

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]

CodePudding user response:

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]))

CodePudding user response:

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)

CodePudding user response:

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]))

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

It’s easier than it seems:

const getSums = (arr) => {
  let result = []
  arr.forEach((el, index) => result.push(el - arr[index   1]));
  return result
}

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

  • Related