How to loop through an array and create a new one based on the firts one’s values

Tags: ,



I want to create a new array that holds the values’s sum of all vowels for every word. The characterLetter function works just fine in finding out how many vowels are in a word, but I don’t know how to create an array where those every word submited has its own correspond vowels’ sum. My goal is to get an array output like this:

Example array= {“anne”, “mike”, “jiana”}

Expected output= {name1= 6, (sum of 1 “A” and 1 “E”) name2= 14, (sum of 1 “I” and 1 “E”) name3= 10 (sum of 1 “I” and 2 “A”)}

Here it’s mi JS code:

function characterLetter(letter, character) {
  let countLetter = 0; 
  if (letter === character) {
    countLetter++;
  }   
  return countLetter;
}

function vowels(arr){
  ///////here I set the value I want for each letter
  let a, b, c, d, e, f, g, h, i, j, k, l, m, n, ñ, o, p, q, r, s, t, u, v, w, x, y, z;
  a=j=s= 1;
  b=k=t= 2;
  c=l=u= 3;
  d=m=v= 4;
  e=n=ñ=w= 5;
  f=o=x= 6;
  g=p=y= 7;
  h=q=z= 8;
  i=r= 9;

  let vowelsArray=0;

  arr.forEach(function (letter) {
    vowelsArray= (a * characterLetter(letter, "a")) + (e * characterLetter(letter, "e")) + (i *characterLetter(letter, "i")) + (o * characterLetter(letter, "o")) + (u * characterLetter(letter,"u")); 
  });   

  return vowelsArray;
}

Answer

Just save the weighting of the needed chars in an object and reduce each individual name:

const weight = {
  a: 1,
  u: 3,
  e: 5,
  o: 6,
  i: 9
}

const names = ['anna', 'peter'];

const result = names.map(name => {
  return name.split('').reduce((sum, char) => {
    if(weight[char] != null) {
      sum += weight[char];
    }  
    
    return sum;
  }, 0);
});

console.log(result);


Source: stackoverflow