Screen out words from one string that appear in the other

Hello everyone, I am a beginner in JavaScript and I have a question about how to filter out two words from one string based on another string.

string1 = ['mango', 'iPhone', 'banana', 'computer', 'apple', 'keyboard', 'strawberry'];
string2 = ['mango', 'banana', 'apple', 'strawberry'];


const string3 = string1.filter(if (word) {})

This is what I have tried so far. I am unsure of what parameters to include in the filter() method. (1) I want to check if any word from string 1 matches with any word in string 2, (2) then exclude those words (3) and store the remaining ones in string 3.

If there are alternative methods to achieve the same result, I would greatly appreciate any suggestions.

Answer №1

To efficiently handle large array sizes, one effective method is to create a hash table (object) using the elements from the second string. Then, filter out the elements in the first string by checking their presence in the hash table.

Check out the code snippet below for an algorithm that operates with a time complexity of O(m+n), where m and n represent the lengths of the arrays:

const string1 = ['mango', 'iPhone', 'banana', 'computer', 'apple', 'keyboard', 'strawberry'];
const string2 = ['mango', 'banana', 'apple', 'strawberry'];

let obj = Object.fromEntries(string2.map(e => [e, true]));
let res = string1.filter(e => !obj[e]);
console.log(res);

Answer №2

To implement a filter, you can use the following code snippet

const filteredResult = stringData.filter(word => !forbiddenWords.includes(word));

If your goal is to eliminate items present in list2 and list3 from list1 simultaneously, you can follow this alternative solution

listOne = ['orange', 'tablet', 'pear', 'laptop', 'banana', 'mouse', 'grape'];
listTwo = ['orange', 'pear', 'banana', 'grape'];
listThree = ['4', '5', '6', 'tablet']

finalList = listOne.filter(word => !(listTwo.includes(word) || listThree.includes(word)));

console.log(finalList);   // ["laptop", "mouse"]

Answer №3

Sort through array string1 to find elements that do not exist in array string2:

string3 = string1.filter(function(val) {
 return string2.indexOf(val) == -1;
});

Answer №4

Ensure that your variable names do not contain any spaces. When using the filter method, it requires a function as an argument and will return elements that evaluate to true when passed through that specified function.

list1 = ['carrot', 'TV', 'potato', 'laptop', 'orange', 'mouse', 'grape']
list2 = ['carrot', 'potato', 'orange', 'grape']

list3 = list1.filter(function(item) {
  return (!list2.includes(item))
})

console.log(list3)

This code snippet generates a new array (list3) from list1, removing any words that exist in list2.

Answer №5

let array1 = ['mango', 'iPhone', 'banana', 'computer', 'apple', 'keyboard', 'strawberry'];
let array2 = ['mango', 'banana', 'apple', 'strawberry'];

|------------|----------------------------------------------------------|
| Vanilla JS | const findDifference = (firstArray, secondArray) => firstArray.filter( item => secondArray.indexOf(item) < 0); |
|            | let output = findDifference(array1, array2);             |
|------------|----------------------------------------------------------|
| Ramda      | let output = difference(array1, array2);                |
|------------|----------------------------------------------------------|
| lodash     | let output = _.difference(array1, array2);              | 
|------------|----------------------------------------------------------|

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

Leverage the power of multiline JavaScript expressions within your React components

I am facing a situation where I have the following React function component source code: return ( result.map(item => ( <tr key={item.id}> <td> {new Date(item.pub_date).getFullYear()} / {new Date(item.pub_date).getMont ...

What is the module system that fabric composer utilizes for its logic JavaScript files?

I am currently in the process of creating a business-network-definition for Hyperledger using Fabric (based on generator-hyperledger-fabric). Everything has been running smoothly so far, but as we move onto our Proof of Concept (PoC), a few questions have ...

ms-card malfunctioning due to data issues

I'm facing difficulties in transferring the data to the template. Although I can access the data in HTML using vm.maquinas and maquina, I am unable to pass it to the TEMPLATE through ng-model. Information about ms-cards was not abundant. Module ang ...

Determining the background image size of a div when the window is resized

I'm facing a problem that I can't seem to solve. I have a div with a background image. <div class="a"></div> I want to make a specific point of this background image clickable. I know I can achieve this by adding a div with a z-inde ...

Displaying local time alongside global time using PHP

I have a challenge - I am storing time in DATETIME format and now I need to display it in the local timezone. Does anyone know how to achieve this using PHP? ...

Combining Angular JS 1 and Laravel 5.2 for seamless integration

Currently, I am in the process of setting up Angular JS 1 with Laravel 5.2 by installing the necessary dependencies using npm. After installation, a node_modules folder was created alongside the app directory. My primary concern is whether it is recommend ...

Sequential selection in Node-firebird is non-functional

I've been testing some simple code sequentially using the Firebird library called "node-firebird." Despite having multiple rows, it only returns 1 row every time. exports.sequentially = (select, db_con_options) => { Firebird.attach(db_con_options, ...

Warning message will appear before navigating away from the page if vee-validate is

Wondering how to create a simple confirmation prompt asking if the user really wants to leave a page that includes a basic HTML form. The HTML Form: <!DOCTYPE html> <html> <head></head> <body> <div id="app"> ...

The useEffect hook is not successfully fetching data from the local db.json file

I'm attempting to emulate a Plant API by utilizing a db.json file (with relative path: src\plant-api\db.json), and passing it from the parent component (ItemList) to its child (Item) but I am facing an issue where no data is being displayed ...

I want to initiate a Python script by clicking a button on my HTML page with the help of Ajax

Here is my JavaScript code: function executePython() { alert("executed"); $.ajax({ url: "http://localhost:5000/app.py", type: "POST", ...

I seem to be encountering an issue with storing data properly within the for loop - can anyone point out where I may

Within my code, I am iterating through results.data.data.length and successfully retrieving the correct data while storing it appropriately. The data: param1 = [6, 27, 34, 22, 23, 25, 28, 24, 26, 30, 29] // => array length 11 The issue arises when att ...

Error: Unable to access attributes of an undefined object (specifically 'headers') in the Next.js evaluation

I encountered an issue with next js TypeError: Cannot read properties of undefined (reading 'headers') at eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:254:61) Snippet of the pro ...

We were caught off guard by the TypeScript error: an unexpected token showed up when we were expecting a constructor,

Trying to implement a function within a class in TypeScript. class Test { function add(x: number, y: number): number { return x + y; } } Encountering an error message stating: TypeScript Unexpected token, A constructor, method, access ...

How can I send dynamic props between pages using Next.js?

I am currently exploring Next.js and attempting to create a page (index.js) that fetches data about different countries and then displays this information. I would like each country element displayed on the page to have a button that leads to another page ...

Retrieve items from a JSON file based on the user input ID in a React project

Hi there, I'm looking for guidance on how to extract items by name from a JSON file based on user input. The JSON file contains both an id and name for each item. My goal is for the user to enter a number, which will then display the corresponding ite ...

A guide on showcasing nested arrays data in an Angular application

info = [ { list: [ { title: 'apple'} ] }, { list: [ { title: 'banana'} ] } ] My goal here is to extract the list items. Here is how they are structured. desired r ...

Material-UI: Issue with AppBar background color not changing when specifying type as 'dark' in createMuiTheme

When I change the theme by switching the value of theme.palette.type to 'dark', I noticed that all white components switch to a dark color, but not for components like AppBar which have a primary color of #3f51b5 as their default. I assumed that ...

PHP code to display "ed elements that do not adjust height"

A php script is being utilized to scan a directory and populate a gallery with all the images. Within the <div id="content"> tag, the function <?php create_gallery("path"); ?> loads all the images. The issue arises when the height of the <d ...

How to disable a specific array of dates in Ant Design range picker

Is there a way to block dates prior to the current date and specify certain dates that should also be disabled on the calendar? For example, I need to prevent selection of: Today: 2018-07-30 Dates to disable: [2018-08-10, 2018-08-12, 2018-08-20] When t ...

Using jQuery to select a nested element in HTML

After choosing $("a.tp[programm='" + programm + "']"); I am looking to target the nested element span.thump and update its text content. How can I achieve this? <h4><a programm="74" class="tp" href="#"><img src="/images/tuo.png ...