Paulos3000
Paulos3000

Reputation: 3545

Matching anagrams and pushing to an array

I have a given word, that I want to match against a given list of words, mainList, and establish which words of that given list are anagrams of the given word, and add them to another list, subList.

I feel like my method to do this is fine, but it returns an unexpected result.

For example...

var word = 'master';
var mainList = ['stream', 'pidgeon', 'maters'];
var subList = [];

Then I take the word, split to an array of letters, alphabetise, and join back into a string. With this string I should be able match against any possible anagrams (which I will covert in the same way).

var mainSorted = [];

  for (i = 0; i < word.length; i++) {
     mainSorted = word.split('').sort().join();
  }

This is where it goes wrong. I loop through the mainList array trying to establish if a given item, when converted, matches the original. If so, I want to push the word to the subList array.

  for (var i = 0; i < mainList.length; i++) {
     var subSorted = mainList[i].split('').sort().join;
     if (mainSorted === subSorted) {
        subList.push(mainList[i])
     }
  }
  return subList;

...and the value I expect to see for subList is: ['stream', 'maters']

Yet I am returned an empty array instead.

I've gone through this so many times and I cannot see what's going wrong, would really appreciate some help!

Also, I'm aware there's probably more eloquent methods to do this (and I welcome any suggestions) but primarily I want to see where this is going wrong.

Thanks in advance.

Upvotes: 0

Views: 114

Answers (1)

Jaromanda X
Jaromanda X

Reputation: 1

You forgot () at the end of join

var subSorted = mainList[i].split('').sort().join; 

should be

var subSorted = mainList[i].split('').sort().join();

One non-issue is

for (i = 0; i < word.length; i++) { mainSorted = word.split('').sort().join(); }

doesnt need to be in a loop

 mainSorted = word.split('').sort().join();

alone suffices

as a bonus, here's a tidier way of doing what you are doing

var word = 'master';
var mainList = ['stream', 'pidgeon', 'maters'];

var mainSorted = word.split('').sort().join();

return mainList.filter(function(sub) {
    return sub.split('').sort().join() == mainSorted;
});

Upvotes: 2

Related Questions