What is the best way to extract "true" values from an array and store them in a new array during iteration?

I am currently enrolled in a Codecademy course and I am facing a roadblock. My main goal is to gain a solid grasp of JavaScript.

The current task at hand is as follows: "There is an array of unnecessary words. Your goal is to iterate over the array and filter out these words. Store the remaining words in a new array named betterWords. There are multiple approaches you could take to accomplish this."

Here is my progress so far, but I am struggling with how to return the "necessary" words to the "betterWords" 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\'s 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);
    
storyWords.filter(function() {
  let betterWords = [];
  for (wordsIndex= 0; wordsIndex < storyWords.length; wordsIndex++) {
    for (unnecessaryWordsIndex = 0; unnecessaryWordsIndex < unnecessaryWords.length; unnecessaryWordsIndex++) {
      if (wordsIndex != unnecessaryWordsIndex) {
                    
      }
    }
  }
});

Would using .splice() to remove the items and then .map() be the right approach?

I am aware that I might be overcomplicating this process, which tends to be my way! Any suggestions and explanations would be greatly appreciated. Thank you in advance!

Answer №1

The functionality of the filter function seems to be causing some confusion. It's recommended to try something like this instead:

let filteredWords = storyWords.filter(function(word) {
    if (overusedWords.includes(word)) return false;
    if (unnecessaryWords.includes(word)) return false;
    return true;
});

Remember, when using filter, the original array remains unchanged.

Answer №2

To streamline your word selection process, you can utilize the Array#filter method and incorporate Array#includes to determine if a word is not present in the unnecessaryWords and overusedWords arrays.

var 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\'s 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.',
    overusedWords = ['really', 'very', 'basically'],
    unnecessaryWords = ['extremely', 'literally', 'actually' ],
    storyWords = story.split(' '),
    betterWords = storyWords.filter(word =>
        !unnecessaryWords.includes(word) &&
        !overusedWords.includes(word)
    );

document.body.appendChild(document.createTextNode(betterWords.join(' ')));

Answer №3

When using the filter method, remember that it returns a new array. Therefore, you can create a new array by assigning the result of the filter operation to a variable like

let betterWords = storyWords.filter(...);

Answer №4

It is not advisable to store overusedWords and unnecessaryWords as arrays. Searching through these arrays has a time complexity of O(n) because you need to check each element of the array individually. By converting these arrays to sets, you can achieve O(1) search operations. While this may not make a noticeable difference for small inputs, it ensures a clean and efficient approach, especially for handling large lists of overused/unnecessary words.

Another suggestion is to split the text on non-word characters instead of just spaces. This ensures that words like "literally," (with punctuation) are included in the analysis.

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\'s 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'];

const toRemove = new Set(overusedWords.concat(unnecessaryWords));
const filtered = story.split(/\W+/).filter(e => !toRemove.has(e.toLowerCase()));

console.log(filtered);

You can achieve the same result with a regex one-liner that disregards case and offers some potential options for replacement/cleanup:

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\'s 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'];

const result = story.replace(new RegExp(
  "(" + overusedWords.concat(unnecessaryWords).join("|") + ")[^a-zA-Z]*", "gi"
), "");

console.log(result);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

the navigation process in $state was not successful

In order to navigate from page A to B, I included the following code in my page A (history.html) view: <a href="#/history/{{data.id}}"> <li class="item"> {{data.items}} </li> </a> In my app.js file, I set the state as ...

Encountering a random MS JScript runtime error message after a few alerts

Encountering this issue when clicking the "Ok" button on an alert window. Error message: Unhandled exception at line 1, column 1 in a lengthy URI Error code: 0x800a138f - Microsoft JScript runtime error: Object expected This problem is occurring within ...

Join our mailing list for exclusive updates on Angular 6

ingredients : Array additionalIngredients : Array In my code, I have two different methods for subscribing: this.ingredients.valueChanges.subscribe(val=> { console.log(val); } this.additionalIngredients.valueChanges.subscribe(val2=> { console.lo ...

`Vue function is unable to find the definition of a variable`

I am struggling with utilizing a variable in a vue 3 application that has been emitted by a component called Mags. The variable is functioning properly in the importMags function, however, I am unable to access it within the handleSubmit function. It consi ...

What is the process for transforming a list of strings into a JSON array using a shell command?

Is there a more efficient way to parse and convert a list of strings into a JSON string array using shell commands? '["test1","test2","test3"]' and output it as: test1 test2 test3 I have attempted the following method: string=$1 array=${string# ...

Unusual outcome observed when inputting a random number into HTML using JavaScript

In my HTML file, I am trying to input a number within 50% of a target level into the "Attribute" field. Here is the code: <!DOCTYPE html> <html> <body> <input type = "number" name = "playerLevel" onchan ...

Getting JSON key and value using ajax is a simple process that involves sending a request

There is a JSON data structure: [{"name":"dhamar","address":"malang"}] I want to know how to extract the key and value pairs from this JSON using AJAX. I attempted the following code: <script type="text/javascript> $(document).ready(function(){ $ ...

Tips for retrieving additional values from a chosen variable in Angular 10

Here is an array I have: export const Glcode = [ { id: 1, Type: 'Asset', Name: 'Cash at Head Office', code: '10018' }, { id: 2, Type: 'Asset', Name: 'POS ACCOUNT ', code: '10432' }, { ...

What is causing the issue of subdomains not functioning properly in express.js?

Currently, I am conducting some local experiments and have made changes to my hosts file. Here are the entries: 127.0.0.1 example.dev 127.0.0.1 www.example.dev 127.0.0.1 api.example.dev Below is the code I am using: var subdomain = req ...

Webpack-hot-middleware increases the number of event listeners exponentially

When configuring my new development environment (node server + client with vanilla js), I encountered an issue with webpack-hot-middleware for live reloading front-end changes. The problem arose when using code like: $button.addEventListener('click&a ...

The raycaster is experiencing issues when used with multiple cameras in the Three.js library

I am currently developing an application similar to the threeJs editor. In this project, I have implemented four different cameras, each with unique names and positions. Here is an example of one of the cameras: cameras['home'] = new THREE.Combi ...

Tips for successfully sending a variable through setOnClickListener

Overview: The main layout, map_midvalley_g, contains 8 image buttons that can be clicked. Using a for loop on the data retrieved from the server, the color (green or red) of the image buttons is set. Clicking on any of the image buttons will trigger a popu ...

Loading drop-down menu content after making an AJAX request

I understand that AJAX functions asynchronously (hence the "A" in AJAX). I have placed all the code that relies on the result of the AJAX call inside the success callback function. However, even after making the call, the select dropdown box is not being p ...

Steps to programmatically update Node modules:

I am looking to incorporate the use of npm update within a script. Take a look at my code snippet below: var npm = require('npm'); npm.load(function () { npm.commands.outdated({json: true}, function (err, data) { //console.log(data); npm ...

The issue with Lodash isEqual arises from the constructor specified by Angular

Currently, I am utilizing Lodash _.isEqual for performing a deep comparison between a local JavaScript object and another JavaScript object fetched through angular $get. The initial code indicates that the objects are not the same: $get({...}, function ( ...

When passing req.body to another file for processing, it is displaying as undefined in node.js

Currently tackling an issue with a project involving nodejs where the request body is showing up as undefined Fetching some data on the client side, but encountering difficulties Received an error pointing out that the property is either undefined or nul ...

Implementing fastJSON to work with a JSON array

I have been utilizing fastJSON library to extract information from a JSON file I created. The JSON file contains data related to levels of a game project in Unity, although that detail is not crucial. The JSON content is as follows: {"1": { "backgroun ...

Having trouble syncing a controller with AngularJS

Despite numerous attempts, I am still struggling to make a single controller function properly. Lately, I've been working on Angular projects and no matter what I do, my controllers just won't cooperate. In my latest project, everything is withi ...

load a particular section of another website into my own div

Similar Question: Ways to bypass the same-origin policy I've been looking for a way to load a specific div from another website using this code. Can anyone provide an example of how to do this on jsfiddle? $.ajax({ url: 'http://somethin ...

Customizing blockquote styling in QuillJS with a unique class

Currently, I am exploring a method to include a custom class when the user selects the blockquote toolbar button. When the blockquote is clicked, it generates the following element: <blockquote class="ql-align-justify">this is my quoted tex ...