Ranking word in array

Tell us what’s happening:

I am not able to understand why it is not working and I follow all instructions
it is also giving right alphabetical order of word from the array

Your code so far


function namesScores(arr) {
let alphabet = ' ABCDEFGHIJKLMNOPQRTSUVWXYZ' ;
// sorting in alphbetical order
arr = arr.sort(function(a,b){
if (a > b)
return 1 ;
else if (a == b)
return 0 ;
else 
return -1 ;
}) ;
// decleraing variables
let a = [] ;
let result =0 ;
let sum =0 ;
let l = arr.length ; // arr length
// looping 
for (let i=0 ;i< l ; i++){
  for (let j=0 ; j<arr[i].length ;j++){
  result += alphabet.indexOf(arr[i][j]) ;  // adding aplhbet order of arr
}
  
  sum += (i+1)*result ; // multiply order and rank of word in sorted arr
  a.push(sum) ;
  result = 0 ;
}
return sum ;  // return sum
}

// Only change code above this line
const test1 = ['THIS','IS', 'ONLY', 'A','TEST'];
const test2 = ['I', 'REPEAT', 'THIS', 'IS', 'ONLY', 'A', 'TEST'];

namesScores(test2);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36.

Challenge: Problem 22: Names scores

Link to the challenge:

Hi @Sourabh69733. A couple of observations.

  1. There is no need of assigning sorted arr to arr because Array.prototype.sort will sort in place and also return sorted array.
  2. arr.sort() will suffice because you are sorting an array of names which I believe are made up of letters of the alphabet not numbers.
  3. In the code below you are looping through the array of names and then looping through characters of each name and locating index of each character in alphabet and cumulatively adding that index to result. Essentially what you need is the position in alphabet which is index + 1. If the character is A, its index is 0 but its position is 1 because it is the first. Take note .indexOf is case sensitive. You are assuming a long list of names will be capitalized. For this case it appears so but what if a certain name somewhere in the middle isn’t?
for (let i=0 ;i< l ; i++){
  for (let j=0 ; j<arr[i].length ;j++){
  result += alphabet.indexOf(arr[i][j]) ;  // adding aplhbet order of arr
}
  1. What is the use of a.push(sum) ;?
  2. And please watch the video above shared by @jenovs. Your alphabet is off.

maybe you have an issue here

thank you very much
you are completely right
now it is working