Calculating the total of elements in a 2D array using a specified reference value in Javascript

I am faced with a scenario where I have two arrays:

const array = [ 
[1, 7, 'AAA'], 
[2, 5, 'BBB'], 
[3, 2, 'CCC'], 
[4, 4, 'DDD'], 
[4, 9, 'EEE'], 
[4, 2, 'FFF'], 
[5, 8, 'GGG'], 
[6, 2, 'HHH']];

const names = [
[1, 'Joe'],
[2, 'Dave'],
[3, 'Mike'],
[4, 'Sandra'],
[5, 'Sue'],
[6, 'Mary']];

In this situation, my goal is to sum the values in the array[1] based on the value in the first column and list the three-character letters. The desired result should be as follows:

const names = [
[1, 'Joe',7,'AAA'],
[2, 'Dave',5,'BBB'],
[3, 'Mike',2,'CCC'],
[4, 'Sandra',15,'DDD, EEE, FFF'],
[5, 'Sue',8,'GGG'],
[6, 'Mary',2,'HHH']]

Being relatively new to Javascript, I am unsure about the most effective approach for this task. While I have been successful with non-repeating values in array[0], achieving a sum or listing seems challenging.

const counter     = (array,value) => array.filter((v) => (v === value)).length;
const arrayCol    = (array,value) => array.map(v => v[value]);
const sum         = (prevVal, curVal) => prevVal + curVal;

names.forEach ((p,e) => {
array.forEach ((v,x) => (counter(arrayCol(array,0),v[0])===1) ?
(v[0]===p[0]) && names[e].push(v[1],v[2]) : 
(v[0]===p[0]) && names[e].push(array.reduce(sum,0)) );
});

console.log(names);

I believe that the solution lies within utilizing map or filter, but I am seeking guidance on how to proceed. Any advice or pointers would be greatly appreciated. Thank you!

UPDATE: I have reviewed all of the responses provided by Michael Haddad, Nina Scholz, and testing_22, and find them all to be valuable and insightful.

Answer №1

You can effectively utilize the map and reduce functions together, like so:

const array = [[1, 7, 'AAA'], [2, 5, 'BBB'], [3, 2, 'CCC'],[4, 4, 'DDD'], [4, 9, 'EEE'], [4, 2, 'FFF'], [5, 8, 'GGG'], [6, 2, 'HHH']];
const names = [[1, 'Joe'],[2, 'Dave'],[3, 'Mike'],[4, 'Sandra'],[5, 'Sue'],[6, 'Mary']];

const result = names.map(([id, name]) => {
    let values = [];
    let sum = array.reduce((accumulator, [index, number, text]) =>
      (index === id ? (values.push(text), number) : 0) + accumulator, 0);
    return [
      id,
      name,
      sum,
      values.join(", ")
    ]
})

console.log(result)

Answer №2

To optimize the process, you can gather all relevant data for each group and then organize the outcome based on the names array sequence.

const
    array = [[1, 7, 'AAA'], [2, 5, 'BBB'], [3, 2, 'CCC'], [4, 4, 'DDD'], [4, 9, 'EEE'], [4, 2, 'FFF'], [5, 8, 'GGG'], [6, 2, 'HHH']],
    names = [[1, 'Joe'], [2, 'Dave'], [3, 'Mike'], [4, 'Sandra'], [5, 'Sue'], [6, 'Mary']],
    groups = array.reduce((r, [id, value, code]) => {
        r[id] ??= [0, ''];
        r[id][0] += value;
        r[id][1] += (r[id][1] && ', ') + code;
        return r;
    }, {}),
    result = names.map(a => [...a, ...groups[a[0]]]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

One possible strategy to tackle this issue is:

const array = [[1, 7, 'AAA'], [2, 5, 'BBB'], [3, 2, 'CCC'], [4, 4, 'DDD'], [4, 9, 'EEE'], [4, 2, 'FFF'], [5, 8, 'GGG'], [6, 2, 'HHH']];
const names = [[1, 'Joe'], [2, 'Dave'], [3, 'Mike'], [4, 'Sandra'], [5, 'Sue'], [6, 'Mary']];

let result = [];
for (let name of names) {
    let newValue = [...name, 0];
    let matchingItems = array.filter(i => i[0] === name[0]);
    let strings = []; // for lack of a better name...

    for (let item of matchingItems) {
        newValue[2] += item[1];
        strings.push(item[2]);
    }
    newValue.push(strings.join(", "));

    result.push(newValue);
}

console.log(result);

An alternative approach would involve writing custom joining logic (which might enhance readability):

   const array = [[1, 7, 'AAA'], [2, 5, 'BBB'], [3, 2, 'CCC'], [4, 4, 'DDD'], [4, 9, 'EEE'], [4, 2, 'FFF'], [5, 8, 'GGG'], [6, 2, 'HHH']];
const names = [[1, 'Joe'], [2, 'Dave'], [3, 'Mike'], [4, 'Sandra'], [5, 'Sue'], [6, 'Mary']];

let result = [];
for (let name of names) {
    let newValue = [...name, 0, ""];
    let matchingItems = array.filter(i => i[0] === name[0]);

    for (let item of matchingItems) {
        newValue[2] += item[1];
        newValue[3] += newValue[3] === "" ? item[2] : `, ${item[2]}`;
    }

    result.push(newValue);
}

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

Submitting Data Forms with AJAX on dynamically loaded webpages

Issue with Form Submission in Ajax-Generated Page I am experiencing an issue with form submission on a page generated within AJAX. The page contains two forms, #form1 and #form2. The jQuery code for submitting the form is as shown below: jQuery("#form1" ...

Display a single button on hover in Angular 2+ framework

I'm looking to have the 'Edit' button only appear when I hover over a selected row. Here's the code: https://stackblitz.com/edit/inline-edit-change-edit2-j8b2jb?file=app%2Fapp.component.html I want the 'Edit' button to show u ...

Mongoose opts for the __v field over a traditional date field

My current model setup is causing unexpected behavior: const mongoose = require("mongoose"); const Schema = mongoose.Schema; const NewModelSchema = new Schema({ user: { type: Schema.Types.ObjectId, ref: "users", }, date: ...

Is there a way to convert an array of objects with 2 elements into 2 separate arrays?

I am looking to split a single array containing objects with 2 elements into two separate arrays. After making an axios call, I received the following array: chartdata: Array [4] [{"total":3,"month":9}, {"total":5,"m ...

Save the API response data to LocalStorage when the button is clicked

Is there a way to save data retrieved from an API into localStorage when a button is clicked? After executing the following code, I would like to store the obtained result: function getResults(query) { fetch(`https://cors-anywhere.herokuapp.com/https: ...

The proportion in Highchart appears incorrect when utilizing a "logarithmic" y-axis type

I have encountered an issue with Highcharts in my AngularJS application. Specifically, I am using Highcharts JS v7.2.1 (2019-10-31). When I set the y-axis type to "logarithmic," it causes the bars to render incorrectly in terms of proportion. If I don&apos ...

Utilizing the splunk-logging NodeJs package with TypeScript in node v14: A comprehensive guide

I'm currently attempting to integrate Splunk logging with my TypeScript code in NodeJS v14. After referring to the documentation, I came across the following example: var SplunkLogger = require("splunk-logging").Logger; var config = { t ...

In need of styling text using CSS?

Despite setting the CSS to .text { word-wrap : break-word; max-width: 100px}, the text is not wrapping as expected. It is still displaying in a single line. I am anticipating that the large text should wrap onto the next lines. ...

A guide on changing a plus sign into a minus sign with CSS transition

Is there a way to create a toggle button that changes from a plus sign to a minus sign using only CSS, without the need for pseudo-elements? The desired effect is to have the vertical line in the "+" sign shrink into the horizontal line. While I know it& ...

Issues in C program when handling extensive arrays

I am facing a challenge while attempting to execute a simulation that involves a multitude of calculations and values. The issue arises when using large arrays, causing the program to crash even before any variables are declared. It is unclear whether thi ...

In React Native, the conversion from ReadableNativeMap to Double does not allow for direct casting of value for value

I've been working on creating a cool animation effect for the text ams with the help of react-native-reanimated. Although I suspect the issue lies within the Animated component, I'm struggling to identify a solution. https://i.sstatic.net/SYl19. ...

How to extract data from an alert in an Ionic application

I am currently working with Ionic 3 and I have a requirement to implement autocomplete using Google Maps on an input field. Below is the alert that I have in my .ts file: let alert = this.alertCtrl.create({ title: 'Offer a Ride', inputs: ...

AJAX Animated Transition

I'm attempting to implement a transition effect using AJAX, but unfortunately, the effect is not functioning properly. Each of my HTML pages contains a wrapper class and an innerwrap class. Upon clicking on a navbar item, I expect the innerwrap in the ...

No data returned from API call in Next.js and Strapi

Recently, I encountered an issue with my Next.js frontend application that fetches data from a Strapi backend. Despite seeing requests being made in the Strapi developer logs, the retrieved data is empty. Below is a snippet of my Next.js code: import { us ...

Received the error 'Headers cannot be set after they have been sent to the client' upon the second request

I created a web server that acts as a client-side application using socket.io-client and express. This setup is necessary for another project I am working on. The web server emits the posted string and responds by sending the served string when it receive ...

Activate the button solely when the text field has been populated without any spaces

Searching for a solution to my query, but all the suggestions I've encountered don't consider spaces as valid input. In the join function I have, the button should be disabled if the user enters only spaces. A requirement is for actual text inpu ...

What is the best way to transfer data from an array to an HTML table?

I've been working on implementing the Google Contacts API to display all of my contacts. While following a tutorial, I realized that it didn't cover how to actually showcase the data on my website. Additionally, I am using Google App Engine and P ...

Unlock the power of TypeScript's inheritance by utilizing static methods for type

In my TypeScript project, I have two classes: BaseModel and HotelModel. The HotelModel extends the BaseModel class, which provides static methods like findById, all, etc. export default class BaseModel { private collection:string _id:string | undefine ...

Every time I attempt to destructure the state object in react typescript, I encounter the error message stating 'Object is possibly undefined'

Whenever I attempt to destructure my state object in react typescript, I encounter an error stating Object is possibly 'undefined'. When I try using optional chaining, a different error pops up saying const newUser: NewUser | undefined Argument o ...

What could be causing the dysfunction of the jQuery class adding function?

I'm new to using jQuery and I'm trying to add a class to the 'a' tag when the 'li' tag is clicked. However, it doesn't seem to be working as expected. $('.nav-item').click( function() { $(".nav-item a").re ...