Improving a JavaScript filtering function I created a function that compares an array of letters to the alphabet, and returns the letters that are not in the original array.

While this works, it looks somewhat clumsy to me, but I don't know what I'm looking for to improve the code...Is there a way to make it more elegant? Perhaps getting rid of the notPresent array somehow?

getLettersNotInContent(['z', 'a', 'p']);

function getLettersNotInContent(letters) {
  // Filter dups if present
  var uniques = [];
  letters.filter(function(letter) {
    if (uniques.indexOf(letter) === -1) {
      uniques.push(letter);
    }
  });

  // Filter and return the letters that are not present in the content
  var alphabet = ['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'];
  var notPresent = [];
  alphabet.filter(function(letter) {
    if (uniques.indexOf(letter) === -1) notPresent.push(letter);
  });
  return notPresent;
}
You're mixing up two different ways of doing this. The old-fashioned way involves looping through the alphabet and pushing the letters not present into an array:

function getLettersNotInContent2(letters) {
    var alphabet = ['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'];
    var notPresent = [];
    for (var i = 0; i &lt; alphabet.length; i++) {
        if (letters.indexOf(alphabet[i]) === -1) notPresent.push(alphabet[i]);
    }
    return notPresent;
}


The newer way (more elegant but not supported in IE8) uses the filter method with a function that returns true or false:

function getLettersNotInContent3(letters) {
    var alphabet = ['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'];
    return alphabet.filter(function (letter) {
        return letters.indexOf(letter) === -1
    });
}


Your code happens to work because, under the hood, filter also loops through the values of an array in turn. But you're not using it in the intended way.

(In both cases I removed the filtering out of duplicates as this seems unnecessary.) (jsfiddle)