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

Ways to display two tabs in reactjs

My typical app is running smoothly, but I am trying to implement a feature where it launches two tabs upon opening. The first tab should open with a normal path of '/' and the second one with a path of '/board'. Here's an example: ...

Ways to incorporate smooth transitions to content using CSS

I recently created a website for a competition and I am looking to make the text change when a user hovers over a link. While I have managed to achieve the text change, I now want to add a transition to it. I have only used CSS to change the code. Can some ...

How to efficiently store data using ajax and php techniques

I'm currently working on sending data via ajax for the user_question and language input fields. Can anyone help me with the correct way to include this element in the ajax JavaScript code so that I can save the table element value in my database? Tha ...

"Controller's $watch function fails to trigger when new items are added to an array within a directive

Within my code, I have established a two-way binding variable called publish.selected_tags that connects a directive with a controller. To monitor changes in this variable, I implemented a $watch function within my controller: $scope.$watch('publish ...

What is the best way to check for incorrect or missing values when comparing two Arrays?

Can you help me with comparing two arrays, $original and $duplicate? Here is the content of my original array: print_r($original); Array ( [0] => cat423 [1] => dog456 [2] => horse872 [3] => duck082 ) And this is my duplicate array: pr ...

Creating multiple AJAX contact forms can be achieved by modifying the code to accommodate multiple forms on a single page. Here's

My one-page website features 15 identical contact forms all with the same ID, created using basic PHP. Unfortunately, I am facing an issue where AJAX is only working for the first form. When submitting any other form, it simply opens a white page with a "T ...

What is the best way to extract specific information from an API using AJAX and Axios?

I can't figure out what I'm doing wrong when trying to access a URL from an API using Axios. For instance, I'm attempting to select the following URL: "https://media4.giphy.com/media/yy6hXyy2DsM5W/giphy-downsized.gif?cid=482277c2s3j1s8uell6v ...

Error message "Property 'name' does not exist on type '{}'" is encountered when using Ionic/Angular HttpClient and no data type is specified

While working on my Ionic project, I encountered an error in Angular when trying to fetch data from an API using HttpClient. The error message that popped up was 'Property 'name' does not exist on type '{}'.'. Below is the cod ...

The scrolling feature induces a contraction to the left side

Recently, I implemented the code below to fix my menu when scrolling the page: var num = 5; $(window).bind('scroll', function () { if ($(window).scrollTop() > num) { $('.scroll').css({'position':'fixed&apo ...

How to manage print preview feature in Firefox with the help of Selenium in the Robot Framework

Attempting to select the 'cancel' button in the print preview page on Firefox has proven to be a challenge. Despite my efforts, I am unable to access the element by right-clicking on the cancel option. Interestingly, Chrome allowed me to inspect ...

Tips for sorting an array of objects by multiple keys while maintaining the order of each key that comes before

I am looking to create a versatile function that can organize an array of objects based on specified keys, while maintaining the order of previous keys. Here is a sample scenario: const input = [ { a: 'aardvark', b: 'bear', c: 'c ...

What could be causing the appearance of a mysterious grey box hovering in the upper left portion of my image and why is the code only adjusting the size of the grey box instead of the entire

I've been working on embedding some JavaScript into my Showit website to create a drag-and-drop feature that displays a collage/mood board effect. Everything is functioning correctly, but I'm running into issues with resizing the images. There&a ...

Implement a select element with an onchange event that triggers an AJAX

As a newcomer to Javascript, I've been struggling to find a solution to my issue. The goal is to add an additional select option when the previous select option is changed. I attempted to implement the code below, but it's not functioning correct ...

Tips and tricks for effectively utilizing Material UI's sx props in conjunction with a styles object

In my current project, I am working with a styles object that is structured as follows: styles = { color: "#333", fontSize: "16px", }; When applying these styles to a Material UI component like the example below, everything works a ...

How can I make a drop-down field in AngularJS show the current value after populating options in a select control using ng-options?

This conversation centers around an app that can be visualized as, https://i.stack.imgur.com/Y1Nvv.png When a user clicks on one of the stories on the left side, the corresponding content is displayed on the right-hand side. Each story includes a title ...

What is the process for changing one tag into a different tag?

Can someone help me with this issue? I need to change the tags in a given string from <h2> to <h3>. For example, turning <h2>Test</h2><p>test</p> into <h3>Test</h3><p>test</p>. Any suggestions o ...

Creating a PHP for loop to compare elements in an array

Within my PHP script, I have a for loop designed to check numbers that are stored in a database. The data is initially stored as a string and then split using the explode function in php. The code snippet below is intended to return only the amount of stoc ...

ajax is now blocking the use of Window.location

I am facing an issue with window.location while working on an ajax request. Here is the code snippet for my ajax request: function login(){ var u = document.getElementById("username").value; var p = document.getElementById("password").value; ...

Arrange JSON information in an HTML table with distinct header rows for every data category

I have a JSON object with a key:value pair named callRoot. Some examples of values for this pair are @S, @C, and @W. There are multiple objects that share the same value and I want to create an HTML table head row at the beginning of each group and repeat ...

Javascript skips the if-else block when used asynchronously

I'm struggling with an if-else block in my code that is not getting executed as expected. Despite rearranging the code to ensure the if-else condition is met before calling http.get(), I am still facing issues. This problem arises while working with A ...