Is there a way to search through an array of object arrays in JavaScript for a specific key/value pair using lodash or any other function?

I am faced with a task involving an array of objects. Each object has a key that needs to be used to search through sets of arrays containing similar objects. The goal is to determine if all the arrays contain the same value for a specific key in my object. If they do, I want to set that value as the object's value.

Is there a more efficient way to achieve this? Perhaps utilizing a powerful, elegant lodash function?

myValues[] = [{'id': 7, 'score': null}, {'id': 3, 'score': null}];
const searchme[] = /* data fetch*/; 
// sample searchme[] =[
//  [{'id': 1, 'score': 1}, {'id': 2, 'score': 1}, {'id': 3, 'score': 1}],
//  [{'id': 1, 'score': 2}, {'id': 2, 'score': 1}, {'id': 4, 'score': 3}],
//  [{'id': 1, 'score': 1}, {'id': 2, 'score': 1}, {'id': 3, 'score': 1}],
// ];
// searchme[] contains 1-5 arrays like myValues[];
// so searchme[0] = [{'id': 2, 'score': 2}, {'id': 7, 'score': 2}], and so on
// theoretically, each searchme[] array has all the ids all the others do 
// - but a few might be missing

myValues.forEach(v => {

  let score: number = null;
  let started: boolean = false;
  let fail: boolean = false;

  searchme.forEach( anArray => {
    found = anArray.find( search => search.id = v.id);
    if (found) { 
      if (!started) { started = true; score = found.score; }
      else { if (score != found.score) { fail = true; }
    } else { 
      fail = true; 
    }
  });

  if (!fail) { v.score = score; }

});

The current solution works, but it feels quite inefficient. Any suggestions or lodash functions to enhance its performance?:)

Answer №1

One approach is to flatten the searchme array and organize it by ids.

(Using groupBy will create an object where the keys represent the property names and the values are arrays of objects with that key).

Handling instances with the same id but different scores can be tricky. To address this, uniq() can be used to ensure uniqueness based on a specific property.

let searchme = [
  [{
    'id': 1,
    'score': 1
  }, {
    'id': 2,
    'score': 1
  }, {
    'id': 3,
    'score': 1
  }],
  [{
    'id': 1,
    'score': 2
  }, {
    'id': 2,
    'score': 1
  }, {
    'id': 4,
    'score': 3
  }],
  [{
    'id': 1,
    'score': 1
  }, {
    'id': 2,
    'score': 1
  }, {
    'id': 3,
    'score': 1
  }],
];

let grouped = _.groupBy(_.flatten(searchme), 'id')
// now grouped looks like:
// { 1: [ {...} ],           // the one object with id==1
//   2: [ {...}, {...} ],    // the two objects with id==2
//   etc

function scoresForId(id) {
  let matches = grouped[id]
  return _.uniq(matches, 'score')
}

console.log(scoresForId(2))
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>

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

Retrieving results from a Node.js application that utilizes multithreading

A new function called diversify() has been developed to execute an expensive function f() in parallel on all the cores of the machine in which it is being deployed. Additionally, a mechanism has been implemented so that when f() returns a value on one core ...

Learn how to transform the html:options collection into html:optionsCollection

What is the best method to transform this code snippet: <html:options collection='catList' property='catId' labelProperty='catName'> using the <html:optionsCollection> tag? ...

Using Typescript to import Eslint with the `import/named` method

My project utilizes Eslint with the following configurations: parser: @typescript-eslint/parser 1.4.2 plugin: @typescript-eslint/eslint-plugin 1.4.2 resolver: eslint-import-resolver-typescript 1.1.1 rule extends: airbnb-base and plugin:@typescript-eslint ...

Guide to integrating Mongoose typings with Angular 2 webpack starter

As a newcomer, I'm hoping this issue is straight forward. I am currently utilizing the angular2-webpack-starter found on GitHub. Based on the mongoose documentation, it appears that including their JavaScript file allows for accessing a global varia ...

Exploring ways to create additional file upload fields with distinct names through JavaScript

My latest project involved creating a button that allows users to add a file upload field, a separate button to remove a file upload field, and a counter to keep track of the total number of file upload fields. However, it appears that the fields are not b ...

How can you prevent an element from overflowing when employing window.pageYOffset and using a switch case to alter the background color at specified pixel thresholds?

I want the <body> element's background-color to change every 500px as I scroll down. I've scoured the web for answers, but still can't figure out what's going wrong. Please review the code. However, Firefox Browser indicates that ...

Is the required attribute for form submission in Material UI not verifying in another file?

It seems that I may be importing incorrectly because a required field does not display a "please fill in this field" popover when attempting to submit a form. The imported classes are as follows: import * as React from 'react' import FormContro ...

Conceal a table if it has no content

I am dealing with 2 tables that contain various data sets. img01 If both of my tables happen to be empty, I would prefer them to be hidden. img02 Is it feasible to implement this in Angular? If you have a solution for me, I would be eager to give it a ...

Managing a database update when server actions involve various form types

My UI dashboard contains multiple forms like "edit title" and "edit description", each with just one input element. I am looking to streamline database updates and server actions in next js 14, utilizing useFormState on the front end. While I have achieve ...

Enhancing Accessibility for the jQuery Countdown Plugin

Seeking to enhance the accessibility of my website's jQuery countdown, I am striving to adhere to WAI-ARIA guidelines. The specified requirements are as follows: Ensure the area is live so it updates dynamically with the countdown display. Avoid re ...

Building User-Friendly Tabs with Twitter Bootstrap: Add or Remove Tabs and Content on the Fly

Looking forward to any assistance or suggestions... I am utilizing Twitter Bootstrap tabs for organizing information on a form page. Each tab will contain a "contact form" where users can add multiple contacts before submitting the entire form. <div c ...

Accordion elements that are active will move all other content on the page

I am currently working on creating an accordion using the following code: https://codepen.io/rafaelmollad/pen/JjRZbeW. However, I have encountered a problem where when clicking on one of the accordion items, the content expands and pushes the title upward. ...

Enclosing values in JavaScript literals

I apologize for the inconvenience. I am unsure why it is not functioning properly. If I input <button type="button" onclick="document.getElementById("demo").innerHTML = Date()">click</button> the above code does not work. However, if I u ...

Can values from a dgrid store be saved in a variable or displayed in the console?

Currently, I am utilizing the dgrid store to display a grid (dgrid 0.4) on my website. Below is the code snippet that I have implemented: require([ 'dojo/_base/declare', 'dojo/Deferred', 'dstore/RequestMemory', ...

Choose datetime datepicker formatting in ng-pick

Currently, I am utilizing Angular and have incorporated the ng-pick-datetime npm. However, when attempting to adjust the format after selecting a date (dd/MM/yyyy), it consistently displays as (MM/dd/yyyy) instead. I am uncertain about how to rectify this ...

Encountering an issue when deploying a project using node, webpack, express, and mysql to Heroku. The error message states: "Uncaught ReferenceError: regeneratorRuntime is not

I've been going around in circles ever since I started this project, and now the code is all over the place. This is my first time working on a node project without using a framework, and I'm starting to regret not choosing PHP. Anyway, here&apos ...

Watch mp4 clips in various languages with ExpressJs

I have a question regarding streaming videos within my local network. My mp4 files contain multiple audio tracks in different languages. Is there a way to select a specific audio track to stream? For instance, could you specify a language as a query parame ...

Displaying the URL of a link on the screen using jQuery

I am looking for a solution to add a link address after the link itself in a table containing reference links for our staff. I have used CSS to achieve this in the past, but the address was not copyable by users. Instead, I am interested in using jQuery&ap ...

Exploring the contrast between Vuex store WATCH and SUBSCRIBE

Can you explain the main distinction between watch and subscribe, and when it is most appropriate to use one over the other? According to information on the Vuex official documentation, both methods appear to be essentially identical in functionality and p ...

the pause in execution before my function redirects to a different route

Currently, I am developing a page using nodeJs with express which is supposed to display a table. However, I encountered an issue with my variable "allMusique" that contains the data for my page. When trying to access it initially, there seems to be an err ...