What is the best way to verify if all the elements in an array of strings are present within the array?

I am working with two arrays of strings, array1 and array2, that I need to compare. I want to find a way to check if all elements from array2 are present in the elements of array1, and then create a new array based on this comparison. I believe using filter + includes is the right approach for my scenario. I came across a helpful answer related to my question.

To clarify, here is an example of what I am trying to achieve and what the expected result should look like:

array1 [ 'apple_mango_banana', 'mango_apple_banana', 'apple_banana' ]
array2 [ 'apple', 'mango' ]

result ['apple_mango_banana', 'mango_apple_banana' ]

Answer №1

You seemed to mention an array of strings, but your code appears to be handling an array of arrays of strings instead. If we assume it's the latter case, would you approach it like this:

let array = [['apple', 'mango', 'banana'], ['mango', 'apple', 'banana'], ['apple', 'banana']]
let comp = ['apple', 'mango']
let ans = []

for (el of array) {
    if (comp.every(y => el.includes(y))) {
        ans.push(el)
    }
}

console.log(ans)

There may be a more concise way to achieve this, but this method gets the job done.

Answer №2

const array1 = [ 'apple_mango_banana', 'mango_apple_banana', 'apple_banana' ]
const array2 = [ 'apple', 'mango' ]

const goal = [ 'apple_mango_banana', 'mango_apple_banana' ]

let result = array1.filter(item1 => array2.every(item2 => item1.includes(item2)))

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

Aborting HTTP POST requests in IE due to error code 0x2ee2

Currently, I am utilizing angularjs for file uploads to my API. The page features a multi-file select option where users can choose one or multiple files. Upon selection, the page initiates calls to the api and uploads each file individually using requests ...

Searching through an array for multiple values on the same key

I am currently working on dynamically generating a listview in jQuery. So far, I have been successful in creating the entire list dynamically. However, I now face the challenge of filtering, searching, or reducing my initial data: var recipes = [ { "name" ...

Eliminate placeholder text when the tab key is pressed

I'm currently facing an issue with a textarea that has a placeholder and the Tab key functionality in Internet Explorer. I've included placeholder.js to make it work, but when I repeatedly press the tab key and focus on the textarea, the placehol ...

I am looking to showcase the data retrieved from an API by arranging it into columns with automatic data filling in a project using React.js and MySQL

When using the onKeyUp event to trigger an API call without submitting the form, I successfully fetched data in response if the mobile number matched. However, I am struggling to understand how to display this data as a default value in columns. I have tri ...

Ways to Retrieve Material-UI Date Picker Data

I am struggling to figure out how to set the value selected by the user in a material-ui datepicker to state. Any help would be greatly appreciated. Currently, this is what I have been trying: The datepicker component code looks like this: <DatePicke ...

Received TypeError: Unable to call reset function - issue clearing input field post ajax request

Having Trouble Clearing Input Fields After AJAX Request: $.ajax({ type: "POST", url: "river_flow.php", data: { username: $("#username").val(), idv:$("#idv").val(), comment: $("#comment").val()}, cache: false, success: function(da ...

What is the best way to compare two date strings with the format dd/mm/yyyy using JavaScript?

When attempting to compare a "Date" type of data with an "Any" type of data, the comparison is not functioning as expected. The date is retrieved in the following code: var today = new Date(); var dd = String(today.getDate()).padStart(2, '0'); v ...

What is the significance of the -infinity value in the JavaScript console?

Recently, while learning JavaScript ES6, I came across a strange result of -infinity on my console when running the following code: let numeros = [1, 5, 10, 20, 100, 234]; let max = Math.max.apply(numeros); console.log(max); What does this ...

Difficulty encountered in altering button color when the password and confirm password fields are the same in a Vue.js project?

password: '', confirmPassword: '', computed: { empty() { return this.user.password === '' || this.user.confirmPassword === ''; }, equal() { return this.user.password === this.user.confirmPass ...

encountered net::ERR_EMPTY_RESPONSE while attempting to locate a CSS file within an AngularJS directive

Every time my webpage attempts to access the css file from a directive, I encounter a net::ERR_EMPTY_RESPONSE. I have implemented door3's on-demand css feature, which allows for lazy loading of css files only when necessary. This feature works flawle ...

Error encountered in vue.js due to a ReferenceError when the resize event is used

I'm having trouble obtaining the window height when resizing, and I keep encountering the error ReferenceError: calcOfSliderHeight is not defined. Can someone explain what's happening? Here is my code: let example = new Vue({ el: '#exam ...

Reordering images using jQuery leads to a malfunctioning reloading of images

I am in search of the most effective approach to alter the src attribute for multiple images on a page post-loading. Essentially, I need to reorganize them for better display. In their initial arrangement, they are presented as follows: 1 5 9 2 ...

Merge identical data into a unified field within a table

I have a table that displays different colors and their quantities. I would like to merge rows with the same color into one row, with the total quantity shown in that row. For instance, if there are 2 "black" colors with quantities of 5 and 2, I want to c ...

The JavaScript promise remains in limbo, neither resolving nor rejecting, seemingly stuck for unknown reasons

In the process of developing a node script, I encountered an issue where the images were not being ordered according to the calculated score value. The score is determined by a function named getImageScore(), which unfortunately takes a considerable amount ...

Trouble with ScrollTo animation on div with adjustable offset top feature - seeking assistance

Having trouble navigating to the correct slide when clicking the right button on the navigation menu. Clicking the menu button displays a list of links. Clicking on a link for the first time will take you to the correct slide, but if you try clicking a dif ...

Increasing an element in an array of objects using MongoDB and Mongoose

In my possession is a document structured as follows: { "id": "12345", "channels": [ { "id": "67890", "count": 1 } ] } My objective is to increase the count of a specific channel by one. When a user sends a message, I must locat ...

Unique rephrased text: "Varied wrapping styles in both

Feeling frustrated with a seemingly commonplace issue. Despite the thousands of times it has been asked before, I can't seem to find an answer on Google. I wanted to neatly display my text within one of my cards, but so far I've only achieved th ...

What is the best way to store the result from a JavaScript FileReader into a variable for future reference?

I am currently facing an issue uploading a local .json file to my web application. I have managed to display the file in the dev tools, but I am unable to make it accessible for further use. It seems like the problem lies in how I handle (or fail to handle ...

Updating a specific array element in MongoDB by its id

I've been attempting this task since yesterday without success. I have two distinct Schemas - the User Schema and the Vital Signs Schema. The Vital Signs Schema is nested inside the User Schema as an array. My goal is to modify a specific vitalSigns ...

Creating interactive lists on Android devices with PhoneGap and jQuery Mobile

I am facing an issue with my code. It works perfectly in Chrome, but when I try to run it on Android, the alert("test") function is never called. I created an apk using PhoneGap and am also using jQuery Mobile. Can anyone help me figure out what I am missi ...