Determine if the first four characters of two arrays in Javascript are identical

http://jsfiddle.net/kg0bs9r7/

I am working on a quiz where I have three unordered lists of images stored in arrays. The goal is to drag and drop the images into the correct columns or arrays.

var arrays = [
['apple_0.jpg', 'orange_1.jpg', 'banana_0.jpg', 'pear_4.jpg', 'fish_5.jpg', 
 'pancake_7.jpg', 'taco_8.jpg', 'pizza_9.jpg'],
['taco_2.jpg', 'fish_5.jpg', 'apple_0.jpg', 'pizza_3.jpg'],
['banana_6.jpg', 'pizza_4.jpg', 'fish_3.jpg', 'apple_0.jpg']
];

var result = arrays.shift().filter(function(v) {
  return arrays.every(function(a) {
    return a.indexOf(v) !== -1;
  });
});

document.write('<pre>' +
           JSON.stringify(result,null,4)
           + '</pre>');

Currently, the code works only when the full object name matches exactly, for example, "apple_0.jpg".
Objective: My objective is to find all instances of apple, fish, and pizza regardless of the suffix (_[variable].jpg).

For example, searching for substrings within the object array.

Answer №1

To standardize the array, extract the relevant values and condense it by identifying common elements.

const
    arrays = [['apple_0.jpg', 'orange_1.jpg', 'banana_0.jpg', 'pear_4.jpg', 'fish_5.jpg', 'pancake_7.jpg', 'taco_8.jpg', 'pizza_9.jpg'],['taco_2.jpg', 'fish_5.jpg', 'apple_0.jpg', 'pizza_3.jpg'],['banana_6.jpg', 'pizza_4.jpg', 'fish_3.jpg', 'apple_0.jpg']],
    result = arrays
        .map(a => a.map(s => s.slice(0, s.indexOf('_'))))
        .reduce((a, b) => a.filter(Set.prototype.has, new Set(b)));

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

Typing into an autocomplete suggestion influences the activation of the submit button

Currently, I am implementing the autocomplete functionality with the google.maps.places.Autocomplete API to allow users to easily find addresses. However, when a user selects an item from the dropdown using the keyboard and hits enter, it affects the submi ...

Simply upload a file and send it to a specific URL by using the drag and drop functionality in HTML

After successfully implementing the drag and drop functionality, my next challenge is figuring out how to upload and post the file to a URL with specific parameters. Usually, if I had a form available, I could do it like this: <form enctype="multipart ...

Locate relevant information within the arrays through the process of filtering

For my collection, I am looking to match the operator_name based on date and then further narrow it down by matching shift_name within an array { "_id": "5eb301bc0218ff48b724a486", "date": "2020-07-02T00:00:00.000Z", "shift_wise": [{ "_id": ...

Python Error Caused by Iterating Through an Array

I am struggling with a Python code that is supposed to take two simple arrays, apply them to a function, and store the results in a new array. Despite trying various solutions from Stack Overflow, I keep encountering an "index 15 is out of bounds for axi ...

I want to use the enter key for posting, but also have the ability to use the shift and enter key to create a

$("#post_text").keydown(function(e){ // Checking if Enter key was pressed without shift key if (e.keyCode == 13) { // Prevent default behavior e.preventDefault(); } if (e.keyCode == 13 && !e.shiftKey) { alert('test'); } }); I a ...

Using C# and Javascript with Selenium

As we delve into our project, we are exploring the best approach for testing between these two options: 1. Selenium with C# 2. Selenium with Java Script Upon researching, I discovered that using C# requires Selenium libraries and NUnit framework. However, ...

Having trouble reaching the AngularJS animation class breakpoint for removeClass or addClass operations

Can anyone help me figure out why my animation class isn't triggering in this codepen? I can access the controller methods fine, but the animation class doesn't seem to work properly. Any ideas on what I might be missing? Check out the codepen w ...

Error injecting angular.bootstrap in Angular 1.6.5 version

I have a MeanJS.org skeleton app that I've transformed into hapi-js from express, switched to postgres from mongo, and incorporated OAUTH for authentication (mainly because I liked the server/client module folder structure - haha). Everything seems t ...

Firestore - Using arrayUnion() to Add Arrays

Is there a way to correctly pass an array to the firebase firestore arrayUnion() function? I encountered an issue while attempting to pass an array and received the following error message: Error Error: 3 INVALID_ARGUMENT: Cannot convert an array value ...

Querying a collection with a bulk request using Mongoose Cursor

My current challenge involves working with rxJS and handling bulk HTTP requests from a database containing over 1 million documents. The code I have is relatively simple. I am pushing all the documents from the collection into an array called "allPlayers" ...

Check out this handy guide on how to use jQuery for sliding effects: [link

My expertise in JS or jQuery is limited, so I am reaching out for your assistance. Take a look at this Slide Example for reference. Can you provide guidance on how to create a similar sliding effect with jQuery using the link provided? ...

Get all keys from an associative array by conducting a search in PHP

Below is an array example: Array ( [0] => Array ( [name] => 'item-1' [type] => typeA [ids] => Array(123, 456, 999) ) [1] => Array ( [name] => &apos ...

Instead of pushing multiple items, focus on pushing only one item at a time

I've encountered an issue while attempting to add a new item to my favlist. Using a for loop, I check if the item already exists in the favlist. However, instead of adding the new item only once, it ends up being added multiple times. What would be ...

Discovering the presence of two values within a single object array with the power of JavaScript

My challenge involves handling an array containing flight details such as origin, destination, and ticket cost. I am attempting to display the specific flight details for a given origin-destination pair. For instance: if the user chooses Bangalore as the o ...

Obtain element values using Protractor and WebDriverJS and store them in an array of objects

Coming from a Java+WebDriver background, I am new to Protractor, WebdriverJS, and Jasmine. In the image displayed, my goal is to hover over all bubbles and retrieve the tool tip values (city, sold, connected), assign them as objects to an array, and return ...

What is the most effective way to share a Node.js application via email?

After completing my nodejs application using JavaScript and generated with express generator, I was required to submit it on the university network. However, when my supervisor attempted to run the application, it did not display properly in Chrome. The ...

What about an external ui-grid-menu-button option for customizing the

Looking for a solution to separate the ui-grid-menu-button from the top right of the table and position it elsewhere? Check out this Stack Overflow question from a year ago which unfortunately remains unanswered: External ui-grid-menu-button Struggling t ...

Upon calling the method, an undesirable page refresh occurs

I have been experimenting with dynamically generating additional input fields using vuejs when a user clicks a button. Initially, my code functions properly by creating more fields, but unexpectedly the page refreshes automatically, resetting the user&apos ...

Set a variable to store the loaded 3D object and receive an undefined value in return

I've been working on a function to load 3D objects using three.js. My goal is for this function to return the 3D object once it's loaded, but no matter what I try, I keep getting "undefined". function load3DObject(url, meshMaterial) { let mes ...

Retrieve the customized attribute from the chosen option within the datalist

Is there a way to retrieve the custom attribute "location" of an option selected from a datalist and display it? I understand that for a select element we can use selectedIndex, but how can this be achieved with datalist? <!DOCTYPE html> <html&g ...