Word Filter с использованием методов массива

1
let story = 'Last weekend, I took literally the most beautiful bike ride of 
my life. The route is called "The 9W to Nyack" and it actually stretches all 
the way from Riverside Park in Manhattan to South Nyack, New Jersey. It\ 
really an adventure from beginning to end! It is a 48 mile loop and it 
basically took me an entire day. I stopped at Riverbank State Park to take 
some extremely artsy photos. It was a short stop, though, because I had a 
really long way left to go. After a quick photo op at the very popular 
Little Red Lighthouse, I began my trek across the George Washington Bridge 
into New Jersey.  The GW is actually very long - 4,760 feet! I was already 
very tired by the time I got to the other side.  An hour later, I reached 
Greenbrook Nature Sanctuary, an extremely beautiful park along the coast of 
the Hudson.  Something that was very surprising to me was that near the end 
of the route you actually cross back into New York! At this point, you are 
very close to the end.';

let overusedWords = ['really', 'very', 'basically'];

let unnecessaryWords = ['extremely', 'literally', 'actually' ];

let storyWords = story.split(' ');
console.log(storyWords.length);

let betterWords = storyWords.includes(unnecessaryWords);

Так вот мой JavaScript-код выше.

Это для присвоения класса. Мы узнаем об итераторах для массивов. (В основном методы, определенные здесь: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)

То, что я уже сделал, это создать строку с историей. Затем я сделал два разных массива, один с чрезмерными словами и один с ненужными словами.

Затем я создал массив, который бы взял строку из истории переменных, которая сохраняла каждое слово и помещала его в новый массив, называемый storyWords.

Теперь я пытаюсь создать массив, который удаляет ненужные слова. Я хочу, чтобы Iterate над моим массивом отфильтровывать эти слова и сохранять оставшиеся слова в массиве с именем betterWords.

Как я могу это сделать? Нам сказали не использовать для циклов и использовать итераторы, которые мы узнали. Я уверен, что для этого я должен выполнить какую-то функцию, но я не могу, чтобы жизнь меня поняла.

Прямо сейчас я думаю, что мне нужно использовать либо.filter, либо.includes, но я не уверен, как это сделать.

  • 1
    Что вы пробовали? Вы даже не пытаетесь с простой петлей. Если вы считаете, что вам нужен filter или include - прочитайте документацию и посмотрите, подходит ли она
  • 0
    Помимо вашего назначения, более простым способом было бы регулярное выражение let rg = new RegExp(unnecessaryWords.join(' |'), 'gmi'); let betterWords = story.replace(rg, '');
Теги:
arrays

1 ответ

1

Используйте фильтр Array # с массивом #, включите его внутри и отмените результат.

let story = 'Last weekend, I took literally the most beautiful bike ride of 
my life. The route is called "The 9W to Nyack" and it actually stretches all 
the way from Riverside Park in Manhattan to South Nyack, New Jersey. It\ 
really an adventure from beginning to end! It is a 48 mile loop and it 
basically took me an entire day. I stopped at Riverbank State Park to take 
some extremely artsy photos. It was a short stop, though, because I had a 
really long way left to go. After a quick photo op at the very popular 
Little Red Lighthouse, I began my trek across the George Washington Bridge 
into New Jersey.  The GW is actually very long - 4,760 feet! I was already 
very tired by the time I got to the other side.  An hour later, I reached 
Greenbrook Nature Sanctuary, an extremely beautiful park along the coast of 
the Hudson.  Something that was very surprising to me was that near the end 
of the route you actually cross back into New York! At this point, you are 
very close to the end.';

let unnecessaryWords = ['extremely', 'literally', 'actually' ];

let storyWords = story.split(' ');

let betterWords = storyWords.filter(sw => !unnecessaryWords.includes(sw.toLowerCase()));

console.log(betterWords);
  • 0
    Спасибо! Я ценю, что вы тоже используете синтаксис стрелок.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню