How do I get an array of numbers and letters to show separately the result of the sum of the numbers and the whole word?

2

The array would be the following:

const array_A = ['H',1,'o',2,'l',3,'a']

and what I want to achieve is to see this '6 Hello'.

    
asked by wilanazu 16.10.2018 в 00:52
source

2 answers

7

You can do it like this:

const array_A = ['H',1,'o',2,'l',3,'a']
var palabra = "";
var suma = 0;

array_A.forEach(function(caracter) {
  if (isNaN(caracter)) {
    palabra += caracter;
  } else {
    suma += caracter;
  }
});
console.log(suma, palabra);
    
answered by 16.10.2018 в 00:55
1

here I leave you how it would be done with some functional programming (filter, reduce) and string interpolation (ES6) in case you want to try ...

const array_A = ['H',1,'o',2,'l',3,'a']

let str = array_A.filter(item => typeof item === 'string').join('');
let num = array_A.filter(item => typeof item === 'number');
let sumNum = num.reduce((acc, val) => acc + val);
console.log('${sumNum} ${str}');

Greetings

    
answered by 17.10.2018 в 10:25