Search through the secondary array to find the corresponding value and then combine it with the primary array

I am faced with the challenge of working with 2 arrays in JavaScript. My goal is to identify array objects in the second array that match the Id of an object in the first array and then append these matching objects to the primary object. The additional requirement is to only include the top 3 matching objects based on a certain key value. I attempted this task using Underscore, but it only combined the matching arrays rather than achieving the desired outcome. Any guidance or assistance on how to accomplish the following would be greatly appreciated.

var primaryArray = [
  {
    "Name": "Main 1",
    "Id": "1"
  },
  {
    "Name": "Main 2",
    "Id": "2"
  }
]


var secondaryArray = [
  {
    "name": "Person 1",
    "mainitemId": "1",
    "count": 120
  },
  {
    "name": "Person 2",
    "mainitemId": "1",
    "count": 80
  },
  {
    "name": "Person 3",
    "mainitemId": "1",
    "count": 125
  },
  {
    "name": "Person 4",
    "mainitemId": "1",
    "count": 130
  },
  {
    "name": "Person 5",
    "mainitemId": "2",
    "count": 90
  },
  {
    "name": "Person 6",
    "mainitemId": "2",
    "count": 85
  },
  {
    "name": "Person 7",
    "mainitemId": "2",
    "count": 105
  },
  {
    "name": "Person 8",
    "mainitemId": "2",
    "count": 110
  }
]


var resultArray = [
  {
    "Name": "Main 1",
    "Id": 1,
    "people": [
      {
        "name": "Person 4",
        "mainitemId": "1",
        "count": 130
      },
      {
        "name": "Person 3",
        "mainitemId": "1",
        "count": 125
      },
      {
        "name": "Person 1",
        "mainitemId": "1",
        "count": 120
      }
    ]
  },
  {
    "Name": "Main 2",
    "Id": 2,
    "people": [
      {
        "name": "Person 8",
        "mainitemId": "2",
        "count": 110
      },
      {
        "name": "Person 7",
        "mainitemId": "2",
        "count": 105
      },
      {
        "name": "Person 5",
        "mainitemId": "2",
        "count": 90
      }
    ]
  }
]

Answer №1

If you are looking to retrieve the top 3 items based on their count value, the following code snippet can help in achieving this:

const topThreeItems = primaryArray.map(item => {
    item.people = secondaryArray.filter(peop => peop.mainitemId === item.Id)
                                .sort((a, b) => b.count - a.count)
                                .slice(0, 3);
    return item;        
})

Once implemented, the final result will showcase the desired top 3 items.

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

Transforming a collection of items into a JSON format string

UPDATE: There was a mistake in the programming, please refrain from submitting answers. This question will be removed. If you have already submitted an answer, kindly delete it. I am attempting to submit a form using jQuery and ajax. One of the fields con ...

What is the best way to traverse a JSON object in AngularJS using a for loop?

I am facing an issue with iterating through an array and checking a condition for each element. If the condition is true, I need to return one value, otherwise another value. However, the loop is not terminating when the condition is met. Can anyone assist ...

What is the best way to iterate through values extracted from a string stream using a for loop in C++?

I'm currently working on a program that needs to read an input file using string stream. Inside the file are student names along with their test scores, which I need to calculate the average for. The file may contain any number of test scores for each ...

Displaying the total count of slides available on the webpage

Check out the custom slider I created on this codepen page: http://codepen.io/anon/pen/NqQpjG I have added an additional feature that tracks the total number of slides that have been moved. For instance, if there are a total of 8 slides, the initial va ...

What steps can I take to streamline this code and enhance its elegance in writing?

Working on some practice problems involving higher-order functions, I managed to solve this particular problem. However, the code I used feels somewhat messy and not as elegant as it could be. Is there a better way to combine map and reduce for a cleaner s ...

Troubleshooting a problem with the Jquery Quicksearch plugin on constantly changing web

Quicksearch is pretty amazing... but it faces a usability issue that causes strange behavior. Many users hit enter after entering a search query, which reloads the page without any parameters and destroys the queries. Check this out: Adding: $('for ...

Tips for retrieving a specific property from an array

Using AngularJS, I am trying to fetch the 'name' property from an array using console.log. However, I am facing issues accessing this property in the array and need to be able to access it. angular.module('ob3App.lead') .controller ...

I am currently familiarizing myself with backend routes and everything seems to be going smoothly for the first time around. However, upon attempting to revisit the site for

https://i.sstatic.net/ZOBl6.png https://i.sstatic.net/Xzhej.png Whenever I navigate from the home page to the contact page and then back to the home page, it displays an error message saying the site can't be reached. var http = require("http&q ...

"Clicking on a handler will replace the existing value when the same handler is used for multiple elements in

import React, { useState, useEffect } from "react"; const Swatches = (props) => { const options = props.options; const label = Object.keys(options); const values = Object.values(options); const colors = props.colors; const sizes = p ...

Utilizing a jQuery AJAX request to invoke a web method within a

My goal is to integrate jQuery mobile into an existing ASP.NET webform application. I am currently considering using pure HTML controls to create the jQuery Mobile page. I am aware that when making an AJAX call, I can access code-behind static web methods, ...

generate iframes on secure websites

I'm in the process of developing a bookmarklet. Essentially, it retrieves a snippet of JavaScript code from the server and generates an iframe on websites with different domains. While it operates smoothly on http websites, it appears to be restricte ...

Tips for reversing the order of a v-for loop using Vue.js

I am working with an array called "names" that starts off empty names: [] To add elements to this array using the unshift() function, which adds elements to the beginning instead of the end, I do it like this: names.unshift("Leonardo") names.unshift("Vict ...

Using Express.js to input and store information into a file

I am currently experimenting with writing data to a JSON file using Express.js. Specifically, I am looking to add a new JSON object to the file for each request made. As a beginner in this area, I am feeling quite overwhelmed and uncertain about what steps ...

Controlling versatile URLs within Angular

I am facing a challenge where most parts of the URLs are optional, with the controller remaining the same. The URL structure is dynamic and changes based on the selected filter parameters. For example, it could be /search, /search/min-1000, /search/max-100 ...

Implementing a JavaScript function with parameters onto an element using backend code

Hey everyone, I've run into a strange issue while trying to pass string parameters to a JavaScript function from the code behind. Here is the current code snippet that I believe is causing the problem: thumbnail = "<a href = 'javascript:Remov ...

Utilizing arrays in the label field of Chart.js

Creating a straightforward bar chart using Chartjs 3.x The process involves fetching JSON data from the server, parsing it, and storing specific parts in arrays. See the code snippet below: serverData = JSON.parse(http.responseText); console.log(serverDa ...

Sharing properties across various components with Next.js

I'm still getting the hang of using Next.js and encountering issues with sharing data between components. Currently, I have a setup involving three components: //index.js function App() { const choices = [] for (let i = 1; i < 101; i++) { ...

A guide on invoking a JavaScript function after receiving a response from an AJAX request

I am facing an issue with a $.POST call that returns the name of a function to be executed, however, the function is not being triggered and I'm unsure why. Below is an example: JavaScript file snippet: $(function(){ $.post('test.php&apos ...

In order for Javascript to continue, it must first wait for a request to be completed

I have a beginner question that's been on my mind. I'm currently working on creating a wrapper for an API and I need to authenticate to receive the access token for further requests (please note, the API doesn't use OAuth). Here is a simpli ...

What is the process for embedding a Vue app within another Vue app?

I have been tasked with creating a widget that will be integrated into various customers' websites. Think about something like this: https://i.sstatic.net/3uKwL.png There are 2 constraints: The use of iframes is not allowed The customers' we ...