Attempting to divide a sentence based on the specified output criteria below

I am trying to split a sentence into individual words and create a new array. If the word is found in another array, I want to replace it with an empty string and add space where necessary.

The desired output should look like this:

Arr=["I want to eat", "","", and, "" ]
let str = "I want to eat Banana Apple and Mango";
var array1 = str.split(" ");
var array2 = ["Banana", "Apple","Mango", "hut", "gut"];

const res = array1.map((item) =>  array2.includes(item) ? "" : item);

console.log(res);

Answer №1

Alright, so the resulting array will look like

[ 'I want to eat', '', '', 'and', '' ]
, which is exactly what you're aiming for.

let sentence = "I want to eat Banana Apple and Mango";

var wordArray1 = sentence.split(" ") 
var wordArray2 = ["Banana", "Apple","Mango", "hut", "gut"];

const result = []
var temporaryString = ""
wordArray1.forEach(word => {
    if(!wordArray2.includes(word)){
        temporaryString += word + ' ';
    }else{
        if(temporaryString !== "") result.push(temporaryString)
        result.push("")
        temporaryString = ""
    }
})

Answer №2

If you're aware of the initial index for your result array, you can set it with the necessary value.

let text = 'I love to drink Coffee Tea and Water';
let arr1 = text.split(' ');
let beverages = ["Coffee", "Tea", "Water", "juice", "soda"];
let output = ['I love to drink']; // initialize with known value

// begin loop at specific index
for (let i = 5; i < arr1.length; i++) {
    if (beverages.includes(arr1[i])) {
        output.push('');
    } else {
        output.push(arr1[i]);
    }
}
console.log(output);

Answer №3

There is a unique approach taken here as you continuously build upon a previous version. Using forEach handles this well, similar to how reduce() functions.

let str = "I feel like having Banana Apple and Mango";
var array1 = str.split(" ");
var array2 = ["Banana", "Apple","Mango", "hut", "gut"];
stra = [""];
array1.forEach(e => {
if (array2.includes(e)) { stra.push(''); return; }
let i = stra.length-1 ;
stra[i] += " " + e
})
stra = stra.map(e => e.trim());
console.log(stra)

let result = array1.reduce((b,a) => {
if (array2.includes(a)) b.push('');
else {
let i = b.length-1 ;
b[i] += " " + a
}
return b;
},['']).map(e=>e.trim());

console.log(result)

Answer №4

Give this a shot

let text = "I love eating Pizza, Pasta and Sushi";
const foodList = ["Pizza", "Pasta","Sushi", "Burger", "Fries"];
const separator = "&";

foodList.forEach(food => {
text = text.replaceAll(food, separator)
})

let finalResult = text.split(separator).map(foodItem => foodItem.trim());
console.log(finalResult);

Answer №5

If you're looking to manipulate the given string in a specific way, this code snippet could be useful:

let str = "I feel like having Orange Banana and Kiwi";
var array1 = str.split(" ");
var array2 = ["Orange", "Banana", "Kiwi", "pie", "cake"];

const result = array1.reduce((accumulator, currentVal, i) => {
  const itemExists = array2.includes(currentVal);
  const lastIdx = accumulator.length - 1;
  if(i !== 0 && !itemExists && accumulator[lastIdx]) {
    accumulator[lastIdx] = accumulator[lastIdx] + " " + currentVal;
  } else {
    accumulator.push(itemExists ? "" : currentVal);
  }
  return accumulator;
}, []);

console.log(result);

Visit Array.reduce documentation for more insights on using reduce method.

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

Optimizing TypeScript/JavaScript for both browser and Node environments through efficient tree-shaking

I am currently tackling a TypeScript project that includes multiple modules shared between a browser client and a Node-based server. Our goal is to bundle and tree-shake these modules using webpack/rollup for the browser, but this requires configuring the ...

Is there a way to successfully integrate a JavaScript file that has been downloaded from `npm` or `yarn` into a web client or

Currently, I am following a guide titled "Headless Drupal with React" on Medium. The tutorial itself does not address my specific questions. In the tutorial, it demonstrates importing React and ReactDOM directly from CDN in the .html file. My query revolv ...

Storing dynamic content on a server and retrieving it for future use

I'm working on a webpage that allows users to create elements dynamically and I want to save those elements to the server. When someone else visits the page, I want them to see those saved elements as well. I'm not too familiar with web programm ...

Uploading files asynchronously in Internet Explorer 8

Currently, I am on the lookout for sample code that allows asynchronous file uploads in IE8 using Ajax. While having upload progress would be a bonus, it is not essential. Moreover, I specifically need PHP code to handle the uploaded files on the server ...

Displaying all items in a collection as HTML using Node.js

I am looking to showcase all the items in my mongodb collection as HTML. In the past, I have accomplished this with simpler tasks, such as... router.get('/', function (req, res) { res.render('home', { title: 'Express', u ...

What is the method for assigning 'selective-input' to a form field in Angular?

I am using Angular and have a form input field that is meant to be filled with numbers only. Is there a way to prevent any characters other than numbers from being entered into the form? I want the form to behave as if only integer keys on the keyboard ar ...

A guide to activating double and single click functionality for GridView rows in Asp.net using C#

I have a GridView row in Asp.net and currently have a single click event working on it. However, I now require a Double Click event for my Grid rows. Can anyone provide guidance on how to achieve this? Your assistance is greatly appreciated. ...

Invoke a JSP page using JavaScript

Hello, I'm new to web development and I have a question about calling JSP from a JavaScript file. My project consists of an html file with JavaScript (home.html) and a JSP file (login.jsp). In the home.html file, there are 2 textboxes and 2 buttons - ...

Manipulating the state of the <audio> HTML5 element with Javascript

Are there any Javascript methods available to retrieve information about the current state of an audio tag? For example: Is the audio playing? Has it stopped? Is it muted? Is it paused? I am aware of using play(), pause(), and others, but I'm unsure ...

Receive an HTTP POST request within JavaScript without using Ajax in Symfony 4.1

Searching for a way to handle an event triggered by a PHP post, not through Ajax. I would like to show a spinner when the form is posted using PHP. In JavaScript, it's easy with code like this: $(document).on({ ajaxStart: function() { $('#p ...

Utilize JavaScript to substitute font family with a designated class name

After discovering a code snippet that can change font family based on ID, I am interested in implementing it on my website but with a twist - using classes instead of IDs. <!DOCTYPE html> <html> <body> <div class="myP">This is a ...

To view the following set of three images, simply click on the "load more" button

I'm looking to add a load more button to reveal additional images. Currently, the page loads with 3 images visible, and upon clicking the load more button, the next set of 3 images should be displayed on the screen. Unfortunately, the code I've ...

Displaying a loading animation within a specific div element

Is it possible to use jQuery to insert a div into another div? My goal is to replace the contents of one div with a loading div while waiting for an ajax call to return. <div id="content1">foo</div> <div id="content2">bar</div> < ...

TypeScript - Issue with generic function's return type

There exists a feature in typescript known as ReturnType<TFunction> that enables one to deduce the return type of a specific function, like this function arrayOf(item: string): string[] { return [item] } Nevertheless, I am encountering difficulti ...

How can you direct a user to a specific page only when certain conditions are met?

Currently using React in my single page application. I have a good grasp on how Routes function and how to create a PrivateRoute. The issue arises when I need to verify the user's identity before granting access to a PrivateRoute. My attempt at imple ...

Finding the chosen selection in AngularJs

I've been working on this script for hours and I'm struggling to output the text instead of the value of a select option in AngularJS in HTML through data binding. Despite my efforts, I keep getting the value instead of the text. How can I resolv ...

Retrieve the IDs of all currently logged in users using express.js

Currently, I am working on a project and need to extract a list of user ids of all currently logged in users. I came across a relevant question on StackOverflow at this link. However, I am facing difficulties in accessing the object properties as intended. ...

Using expect() within the .then() function when writing Jasmine unit tests for AngularJS

I'm currently struggling with the .then() function while trying to implement Jasmine unit testing. Here is the code that's giving me trouble: describe("getBuilding", function () { it("checks getBuilding", function () { var id_building = 4; ...

C++ Excluding White Beans

Hey everyone, I could use some assistance with a programming challenge I'm facing in C++. I am working on a code that will break a random string at every point and then count the number of colors (r, b, and w) to the left and right of the break. The t ...

Ways to resolve the error message "Uncaught TypeError: props.options.map is not a function occurring when using a dropdown select

While working on my project, I encountered a strange error with the react select dropdown. Despite following suggestions online to pass an array of objects as options, I'm still facing the same issue. Surprisingly, when I directly input the data fetch ...