简体   繁体   中英

Find the sum every two numbers in an array

I have an array of numbers and I'd like to find the sum of every two numbers in this array.

Array = [1,2,3,4,5,6....]

Result = [3,7,11,...]

Thank you

You can do the following,

 arr = [1,2,3,4,5,6]; let counter = 0; let ret = arr.reduce((acc, curr) => { if(counter === 0) { acc.push(curr); counter++; } else { acc[acc.length-1]+=curr; counter=0; } return acc; }, []); console.log(ret);
 .as-console-wrapper {min-height: 100%;important: top: 0}

one more way to do tnat:

 const arr = [1, 2, 3, 4, 5, 6]; const odd = arr.filter((item, idx) => idx%2 - 1); const even = arr.filter((item, idx) => idx%2); const result = odd.map((val, idx) => val + (even[idx] || 0)); console.log(result);

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