Home > Software design >  How to add numbers in an array separated by a string [`X`]? JavaSript [closed]
How to add numbers in an array separated by a string [`X`]? JavaSript [closed]

Time:09-27

Here's my array = [22, 7, 0, 19, 'X', 19, 8, 12, 4, 'X', 0, 17, 4, 'X', 22, 4, 'X', 2, 11, 8, 12, 1, 8, 13, 6, 'X', 20, 15, 'X', 19, 7, 4, 'X', 21, 14, 11, 2, 0, 13, 14].

An X string separates numbers. What I want to achieve is to summarize the numbers separated by X.

For example:

  • 22 7 0 19 = 48,
  • 19 8 12 4 = 43,
  • 0 17 4 = 21,
  • 22 4 = 26...

Expected Output [53,43,21,26...]

CodePudding user response:

You need to loop through, and build a sum until you get to the next 'X' When you hit the 'X' you add it to the return array

const returns = [];
const arr = [22, 7, 0, 19, 'X', 19, 8, 12, 4, 'X', 0, 17, 4, 'X', 22, 4, 'X', 2, 11, 8, 12, 1, 8, 13, 6, 'X', 20, 15, 'X', 19, 7, 4, 'X', 21, 14, 11, 2, 0, 13, 14];

let sum = 0;
arr.forEach((number) => {
    if(number === 'X'){
        returns.push(sum);
        sum = 0;        
    }
    else sum  = number;
});

console.debug(returns);

I'm assuming this is for a lesson or something I can't imagine a real world situation that would need this so i'd recommend reading up and learning about

Arrays Array.prototype.Push and Array.prototype.forEach

CodePudding user response:

Use Array.prototype.reduce():

const src = [22, 7, 0, 19, 'X', 19, 8, 12, 4, 'X', 0, 17, 4, 'X', 22, 4, 'X', 2, 11, 8, 12, 1, 8, 13, 6, 'X', 20, 15, 'X', 19, 7, 4, 'X', 21, 14, 11, 2, 0, 13, 14],

      {result, runningTotal} = src.reduce((acc, item, idx) => {
        if(item === 'X' || idx === src.length-1){
          acc.result.push(acc.runningTotal)
          acc.runningTotal = 0
        } else {
          acc.runningTotal  = item
        }
        return acc
      }, {result: [], runningTotal: 0})
      
      
console.log(result)

CodePudding user response:

var a = [22, 7, 0, 19, 'X', 19, 8, 12, 4, 'X', 0, 17, 4, 'X', 22, 4, 'X', 2, 11, 8, 12, 1, 8, 13, 6, 'X', 20, 15, 'X', 19, 7, 4, 'X', 21, 14, 11, 2, 0, 13, 14];
let final = []
let sum = 0;
a.forEach(number =>{
if( number !='X') {
sum = sum   number
} else {
final.push(sum)
sum = 0;
}
})

console.log(final);
  • Related