Find similarities between an array of string elements and an array of object properties

Let's dive into this: for the items listed in foo, how can we identify all the positive matches with the string attributes in each object within array bar? Here's a quick example:

var foo = ['one', 'two', 'three'];
var bar = [
        {   
            integer: 1,
            string: 'one'
        },
        {   
            integer: 3,
            string: 'three'
        }       
    ];

Answer №1

To start, create a set including all elements within foo to prevent quadratic complexity:

var fooSet = {};    
for(var i = 0; i < foo.length; i++) {
    var e = foo[i];
    fooSet[e] = true;
}

Next, iterate through bar and collect any matches found:

var matches = [];
for(var i = 0; i < bar.length; i++) {
    var e = bar[i];
    if(fooSet[e.string]) {
           matches.push(e);
    }
}

Once completed, the matches array will store the elements in bar that correspond with those in foo.

For a demonstration, refer to the following live example:

Answer №2

Iterate through one of the arrays and compare each item with the other:

var matches = [],
    i, j;

for (i=0; i < bar.length; i++)
    if (-1 != (j = foo.indexOf(bar[i].string)))
       matches.push(foo[j]);

// matches is ['one', 'three']

If you want matches to hold the elements from bar instead of foo, simply update the .push() statement to matches.push(bar[i]);.

This method assumes that older browsers lacking support for .indexOf() on arrays are not a concern, or that a shim can be utilized.

Answer №3

These two methods are effective, depending on how you intend to manipulate the data.

http://jsfiddle.net/KxgQW/5/

APPROACH ONE

// Deciding to implement both options
var wayOneArrayFOO = Array();
var wayOneArrayBAR = Array();

var fooLength = foo.length;
var barLength = bar.length;

/*THE TRICK*/
// Looping through foo
for(i=0;i<fooLength;i++){

    // Nested loop to iterate over bar while looping through foo        
    for(j=0;j<barLength;j++){
        if(foo[i] == bar[j].string){
            wayOneArrayFOO.push(i);
            wayOneArrayBAR.push(j);    
        }
    }

}

APPROACH TWO

// Storing values of foo and bar respectively
var wayTwoArrayFOO = Array();
var wayTwoArrayBAR = Array();      

/*THE TRICK*/      
// Looping through foo
for(i=0;i<fooLength;i++){

    // Nested loop for iterating over bar while looping through foo       
    for(j=0;j<barLength;j++){
        if(foo[i] == bar[j].string){
            wayTwoArrayFOO.push(foo[i]);
            wayTwoArrayBAR.push(bar[j]);    
        }
    }

}

Answer №4

Here is a code snippet that matches keys from one array to another:

// Define foo & bar arrays here

// Store all the keys from the foo array in a dictionary (object)
var matchSet = {};
for (var item in foo)
{
    var val = foo[item];
    matchSet[val] = 1;
}

// Check if items in the bar array have a matching key in the matchSet
// If so, add it to the matches array
var matches = [];
for (var i=0; i < bar.length; i++)
{
    var item = bar[i];
    if (matchSet.hasOwnProperty(item['string']))
    {
        matches.push(item['string']);
    }
}

// Output the matched strings using node
for (var i in matches)
{
    console.log(matches[i]);
}

Outputs:

match: one
match: three

Please note that this code is intended to be run interactively using node.

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

Transferring data between actions following an AJAX request in Zend Framework

I am currently utilizing an ajax call to communicate with a controller in order to update the number of articles displayed on the webpage. I have established an action within the controller to handle this ajax request. Below is a snippet of the code: publ ...

Is there a way to properly structure a JSON file for easy reading on localhost

I am having trouble with the formatting of my .json file while using backbone.js. I can't seem to pass in the url correctly. PlayersCollection = Backbone.Collection.extend({ model: Player, url: 'http://localhost/STEPS/data/players.js ...

Is it possible to categorize a JSON object based on its properties and then count the occurrences of each property within

I have an array of objects containing booking information and I need to calculate the count of each booking item in every object. const arr = [ { "ID" : 1, "Name":"ABC", "Bookings":[ { & ...

Updating the position of a Leaflet component in React

Seeking advice on incorporating React Leaflet into a PWA project. I am currently developing a Progressive Web App using the React framework and require a map, hence the need for React Leaflet. Here's the scenario: When navigating to the map page, I ...

Steps for making a webpack-bundled function accessible globally

I am currently working with a webpack-bundled TypeScript file that contains a function I need to access from the global scope. Here is an example of the code: // bundled.ts import * as Excel from 'exceljs'; import { saveAs } from 'file-save ...

Does Javascript move beyond the for loop and then return to it?

Currently, I am working on creating a stopwatch in JavaScript that counts by milliseconds using setTimeout. However, I encountered an issue during the initial setup: var time = 0; function main() { for (var i = 0; i < 5; i++) { setTimeou ...

Exploring the capabilities of the jQuery `val()` function alongside the dynamic framework

Whenever I have a JavaScript variable that contains HTML printed from a table on my server, I encounter issues when using it in a jQuery function like val(). The problem arises every time someone enters content with special characters like " or '. Thi ...

Showing the `ViewBag` data within the `@Html.DropDownListFor` method enclosed

I'm currently working with a DropDownListFor that is set up like this: <div class="form-horizontal" id=CurrencyDataBlock> @Html.DropDownListFor(model => model.Code, ViewBag.Currency as SelectList, "--Select Currency--", n ...

The Ajax script seems to be failing to update the PHP file along with its corresponding variable value

I have a simple form where upon clicking the "=" button, I want the calculated value to be displayed in file process.php. However, this functionality is not working for me. It seems that when the "=" button is clicked, nothing happens. The default value in ...

Manipulating and transforming data through Puppeteer's iterative process into an object structure

As a beginner with the puppetteer library, I'm trying to iterate through Amazon reviews and save each comment as an object. Although my code seems to be functioning, it only retrieves the first comment and then stops. async function scrapeProduct(ur ...

Using Node.js to alter an existing JSON file

I have a file named a1.json that contains the following data: { "Key1" : [ { "Key11" : "Value11" , "Key12" : "Value12" }, { "Key21" : "Value21" , "Key22" ...

Swiper.IO pagination indicators not displaying

Why is the pagination not showing up on the image carousel I created with Swiper? Despite being in the DOM, it has a height of 0 and manual changes have no effect. Any suggestions? import Swiper from '../../vendor/swiper.min.js'; export default ...

Troubleshooting issue: Cookie not functioning properly in if statement

Whenever a user clicks on an upload button, I set a cookie value to 1: $('.uploadbtn2').click(function(){ $(this).val("Please wait..."); $.cookie("upload",1,{ expires: 1, path: '/' }); // the page then refreshes a few secon ...

How can you create a table cell that is only partially editable while still allowing inline JavaScript functions to work?

Just a few days back, I posted a question similar to this one and received an incredibly helpful response. However, my attempt at creating a table calculator has hit a snag. Each table row in a particular column already has an assigned `id` to transform t ...

Using Vue.js to send various data to child components through the router

I am facing a dilemma with the nested router setup in my Vue app. Here is a snippet from my router/index.js: { path: "/parent", name: "Parent", component: () => import(/* webpackChunkName: "parent" */ &qu ...

Encountering an issue where the P3D sketch does not function properly when running

Currently, I am in the process of converting a project I developed in Processing [Java Mode] to an online platform for web viewing. The project involves P3D rendering to showcase a 3D environment that allows for rotation and manipulation of three data sets ...

Winston prefers JSON over nicely formatted strings for its output

I have implemented a basic Winston logger within my application using the following code snippet: function Logger(success, msg) { let now = new Date().toUTCString(); let logger = new (winston.Logger)({ transports: [ new (winsto ...

Initiate the printing process by executing the window.print() function. As the document is being

Here's the code snippet : <body> <div class="headerCont noprint"> <div class="headerHold"> <div class="logoCont"><img src="images/logo.jpg" width="104" height="74" alt="Logo"> ...

Excluding a Spec File in Your Protractor Configurations

I have a scenario where I have 10 spec files all named *********.test.js. I need to run tests on all 9 of these files, excluding the file named Idontwantyou.test.js. Currently, I am locating my spec files in the config.file using: specs: ['*.test.js ...

Sequelize - Removing associations from the parent instance

I'm currently looking for a solution to remove specific rows from the database by using the parent model (menu) with multiple children (foods). My goal is to only delete certain rows and not all of them. Menu.js ... Menu.hasMany(models.Food, { as: & ...