How do I get an array with numbers and letters and a space to add up and form a word?

0

The exercise would be like this:

const array_A = ["H",3,"o",4,"l",5,"a",6," ",7,"M",8,"u",9,"n",10,"d",11,"o"]

const array_B = ["s",1,"t",2,"a",3,"c",4,"k"]

const array_C = ["o",1,"v",2,"e",-3,"r","f","l","o","w"]

You would have to see the sum of the numbers and the word with the space in string.

// '63 Hola Mundo

// '10 stack'

// '0 overflow'
    
asked by wilanazu 16.10.2018 в 18:43
source

3 answers

1

You can use the reduce() method in a function that receives a vector and returns an object with the desired output.

function output(array) {
  return array.reduce((out, current)=>{
    typeof current == "string" ?out.text+=current:out.count+=current;
    return out;
  },{text:'',count:0})
}

I leave you a link with an example.

example

    
answered by 16.10.2018 в 20:05
0

You can try the following function that you create:

function reformular(arreglo){
    //variable donde voy sumando los números
    var n = 0;
    //variable donde voy sumando las letras para formar la oración
    var msg = '';
    //Recorres el arreglo
    for(var i in arreglo){
      //En caso de que el elemento actual de la iteración sea un numero entero
      if(/^-?\d+$/.test(arreglo[i])){
        //Sumas el valor que tenia n el nuevo numero encontrado
        n += parseInt(arreglo[i]);
      } else {
        //De lo contrario concatenas lo que tenia msg al nuevo caracter encontrado
        msg += arreglo[i];
      }
    }
    return '${n} ${msg}';
}

This is how you would call it, assuming you have already declared the 3 arrangements as they were in your question:

console.log(reformular(array_A));
console.log(reformular(array_B));
console.log(reformular(array_C));

You can do the function in this other way:

function reformular(arreglo){
    //variable donde voy sumando los números
    var n = 0;
    //variable donde voy sumando las letras para formar la oración
    var msg = '';
    arreglo.forEach(function(item){
      if(/^-?\d+$/.test(item)){
        n += parseInt(item);
      } else {
        msg += item;
      }
    })
    return '${n} ${msg}';
}

It works in the same way the difference is that I use a function of the Array object that allows me to go through the array without having to create an iterative statement or a cycle itself.

    
answered by 16.10.2018 в 19:24
0

Hello, I hope my answer will be helpful or clarify a bit how to work with arrays:

var handle_array = function(arr){
    a1 = arr.filter((element) => {
        return typeof(element) === 'number';
    });

    a2 = arr.filter((element) => {
        return typeof(element) !== 'number';
    });
    return a1.reduce((total, num) => total + num) + " " + a2.join("")
}

a1 = ["H",3,"o",4,"l",5,"a",6," ",7,"M",8,"u",9,"n",10,"d",11,"o"]
handle_array(a1)

Greetings (And)

    
answered by 16.10.2018 в 20:19