简体   繁体   中英

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

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]

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]=cn.'',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]))

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM