user12768182
user12768182

Reputation:

Sorting a sentence by number of vowels in a word and indexing it from the left using javaScript

Example sentence: "My passion is to work towards my goal is the whole idea"

I want to sort the words according to the word having highest vowels will be showed first followed by descending order of the vowels present in it and indexing it from left. Please help me with the javaScript code.

Thanks for the help in advance.

Upvotes: 0

Views: 549

Answers (3)

Titus Sutio Fanpula
Titus Sutio Fanpula

Reputation: 3613

Maybe you can try with this code below:

let string = "My passion is to work towards my goal is the whole idea";
let myarr = string.split(' ');


function mostWolves(word) {
  let count = 0;
  for(let i=0; i < word.length; i++) {
    let x = word[i].toLowerCase();
    if (x === 'a' || x === 'e' || x === 'i' || x === 'o' || x === 'u'){
      count++;
    }
  }
  return count;
}

myarr.sort((a, b) => {

  if(mostWolves(a) > mostWolves(b)) {
    return -1;
  }else if(mostWolves(a) < mostWolves(b)) {
    return +1;
  } else {
    if(a.toLowerCase() > b.toLowerCase()) {
      return +1;
    }else if(a.toLowerCase() < b.toLowerCase()) {
      return -1;
    } else {
      return 0;
    }
  }
});

console.log(myarr);

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386654

You could split, get counting and original index, sort by counting and index, finally take the joined string.

var string = "My passion is to work towards my goal is the whole idea",
    array = string.split(' '),
    hash = array.reduce((o, k, index) => {
        o[k] = { index, count: (k.match(/[aeiou]/g) || []).length };
        return o;
    }, {})
    result = array
        .sort((a, b) => hash[b].count - hash[a].count || hash[b].index - hash[a].index)
        .join(' ');

console.log(result);

Upvotes: 0

Icarus
Icarus

Reputation: 1463

You may split them first, then count the number of vowels then do sorting.

var str = "My passion is to work towards my goal is the whole idea"

var vowels = 'aeiou'

str.split(' ')
    .map(word => [word, Array.from(word.toLowerCase()).filter(char => vowels.indexOf(char) > -1 ).length])
    .sort((_1,  _2) => _1[1] > _2[1]? -1: 1).map(_ => _[0])

 ["passion", "idea", "towards", "goal", "whole", "is", "to", "work", "is", "the", "My", "my"]

Upvotes: 0

Related Questions