UBO
UBO

Reputation: 27

Write a function that should return a new string, containing only the words that don't have the letter "e" in them in javascript

what am I doing wrong in the code that I mentioned below?

My outputs are [ 'What', 'time', 'is', 'it', 'everyone?' ] and [ 'building' ]. These outputs should be string because I used join method. Also the first output is totally wrong.

let removeEWords = function(sentence) {
  debugger
  let arrayedSentence = sentence.split(" ");
  let newArr = [];
  return arrayedSentence.filter(function(el) {
    if (!el.includes("e")) {
      newArr.push(el);
    }
    return newArr.join(" ");
  })

};
console.log(removeEWords('What time is it everyone?')); // 'What is it'
console.log(removeEWords('Enter the building')); // 'building'

Upvotes: 1

Views: 130

Answers (3)

mplungjan
mplungjan

Reputation: 178350

You need to 'filter' and not add to an array - you are using filter as a forEach

const removeEWords = sentence => sentence
  .split(" ")
  .filter(word => !word.includes("e")) // this returns true to return or false to drop
  .join(" ");
console.log(removeEWords('What time is it everyone?')); // 'What is it'
console.log(removeEWords('Enter the building')); // 'building'

Upvotes: 1

Andy
Andy

Reputation: 63569

filter returns a new array of elements that pass the test (ie true/false) provided in the callback - there's no need for a temporary array that push elements into. So all you need to do is return !word.includes('e'); to return a word that doesn't include e.

Note: I've called the variable word as it makes the callback easier to read.

function removeEWords(sentence) {
  return sentence.split(' ').filter(word => {
    return !word.includes('e');
  })
};

console.log(removeEWords('What time is it everyone?'));
console.log(removeEWords('Enter the building'));

Upvotes: 1

Zack Mitkin
Zack Mitkin

Reputation: 356

The way .filter() works on an array is you need to return either true or false. True = Keep, False = leave;

Knowing this, you can refactor this really simply by just doing this:

let removeEWords =  (sentence) => sentence.split(" ").filter((el) => !el.includes("e")).join(" ");

Upvotes: 2

Related Questions