I have exhausted all options trying to filter a 2D array in JavaScript

The 2D array provided is formatted as follows :

[[ONE,1],[QUARTER,0.25],[QUARTER,0.25]]

The desired output should be :

[[ONE,1],[QUARTER,0.5]]

An attempt was made using array.IndexOf but did not yield the expected result

ONE,1,QUARTER,0.25,QUARTER,0.25

Answer №1

Despite the title of your question, it seems like you are looking to calculate the total sum of an array rather than filtering it.

const values = [['ONE', 1], ['QUARTER', 0.25], ['QUARTER', 0.25]];

const sumsArray = values.reduce((sumsArray, item) =>{
  const foundItem = sumsArray.find(([key]) => key === item[0]);
  if (foundItem)
    foundItem[1] += item[1];
  else
    sumsArray.push(item);
  return sumsArray;
}, []);

console.log(sumsArray);

Answer №2

To streamline the array, check for duplicate keys and combine their values.

var array = [['ONE', 1], ['QUARTER', 0.25], ['QUARTER', 0.25]],
    result = array.reduce((r, [key, value]) => {
        var temp = r.find(a => a[0] === key);
        if (temp) {
            temp[1] += value;
        } else {
            r.push([key, value]);
        }
        return r;
    }, []);

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

What is the best way to expand a div in a downward direction exclusively?

My task involves a parent div containing a centered child div. My goal is to have the child div grow downwards only upon clicking it, not in both directions. Initial state of the two divs: https://i.sstatic.net/cWYyV.png Outcome after clicking on div 2: ...

Utilizing JQuery's .Toggle function in conjunction with a stylish CSS transform button

I am trying to create a toggle menu that shows and hides itself without requiring the button to be clicked twice. I have added e.preventDefault(); which solves the issue, but now the button does not transform as intended. $(document).ready(function() { ...

What exactly does "blocking and tackling" refer to in the Angular2 documentation?

As I delved into the online documentation for angular2, I stumbled upon a puzzling term - "blocking and tackling" in the ADVANCED - Angular Module chapter (https://angular.io/docs/ts/latest/guide/ngmodule.html). ... "It's all just basic blocking and t ...

Having trouble getting the JSONP request to render properly, encountering persistent errors

Need assistance with JSONP Rendering to HTML. The request is present in the source code, but I keep encountering errors on the foreach line. Any help would be greatly appreciated. <meta name="viewport" content="width=device-width, initial-scale=1"&g ...

Fade In Effect in Angular 2 Using SwitchCase

Hi everyone, I'm facing an issue with making my switch cases fade in after one is called. Here's what I have so far. When the correct switch case is entered in the input field, I want the current one to fade out and the new one to fade in. How ...

Looking to incorporate new values without replacing them in react.js and mongoDB

function getFilterQuery() { const completedWorkState = WorkflowStates.findOne({title: 'Completed'}); const inProgressWorkState = WorkflowStates.findOne({title: 'In Progress'}); const identifiedWorkState = WorkflowStates.findOne ...

Utilizing the jQuery index for organizing JSON keys

Recently, I came across an interesting issue with a jQuery event handler in my code. When clicked, this specific event creates a JavaScript object based on a list of favorite links: $('#saveFavorites').on('click', function(){ a ...

The error message "Uncaught TypeError: Unable to retrieve the 'length' property of an undefined object in Titanium" has occurred

Here is the data I am working with: {"todo":[{"todo":"Khaleeq Raza"},{"todo":"Ateeq Raza"}]} This is my current code snippet: var dataArray = []; var client = new XMLHttpRequest(); client.open("GET", "http://192.168.10.109/read_todo_list.php", true); c ...

The Vue mixin properties are devoid of content and lack reactivity

Could you please guide me in the right direction if this question has already been asked before? I really hope it's not a duplicate. I have a Vue application that is compiled using Webpack@NPM. In order to pass a property (roles) across all component ...

How can I retrieve the value of a JavaScript variable using Ajax?

Hello everyone! I've been a long-time user of various programming forums, but this is my first time posting. Lately, I created a really simple browser-based game, and when I say simple, I mean it's incredibly basic. The whole game logic resides ...

Struggling with implementing Bootstrap modal JavaScript in Rails 4, nothing seems to work!

This situation has been addressed in numerous posts, but despite my efforts to find a solution among them, I have yet to come across one that works for me. I am faced with the task of opening a modal that requires JavaScript modifications before being dis ...

What is the best way to store a collection of class instances in a serialized format

Is there a way to convert an object that contains a list of objects into JSON format? Error message received: TypeError: Object of type person is not JSON serializable Here's the code snippet in question: import json class person: def __init__( ...

Tips for utilizing MUI Typography properties in version 5

I'm clear on what needs to be done: obtain the type definition for Typography.variant. However, I'm a bit uncertain on how to actually get these. interface TextProps { variant?: string component?: string onClick?: (event: React.MouseEvent&l ...

Fulfill a promise based on a particular event in Puppeteer

I am looking for a way to seamlessly continue my puppeteer code after a particular event occurs. Specifically, I need guidance on how to handle the 'request' event in a synchronous manner. Here is an example of the event code: await page.on(&apo ...

What is the best way to increase incremental values that are nested within each other

A database has been loosely created with a key known as website. Inside this website object, multiple objects exist, one for each dynamically generated website. An illustration of how the database might appear is shown below: website: { google.com: { ...

How can I display a "loading..." message as a temporary placeholder while waiting for my Apexcharts to load?

I've spent a day trying to solve this issue but couldn't find a solution. Any help would be greatly appreciated. Recently, I was working on creating a cryptocurrency tracker in React. I successfully built a table that displays multiple currencie ...

Creating dynamic routes in react-router-dom using conditions

I'm currently developing an application using react-router-dom for navigation. I've encapsulated all my <Routes> inside a container provided by Material UI. However, I want my home page to be outside of this container so that I can display ...

When utilizing DomSanitizer, Angular2 suddenly ceases to function properly

I've been working with Angular 2 and TypeScript. Everything was going well until I encountered an issue with my pipe, which is causing the DomSanitizer to interfere with the (click) event functionality. Even though the (click) code appears intact in ...

Retrieve the text content of a datalist option by accessing the label with jQuery

Utilizing data from a Json, I am populating a data-list in html. The options are added to the data-list with both value and label text. Upon clicking an option, I aim to insert both the value and text into a form text field. While accessing the option&apo ...

What significance does the slash hold in a package name when using require for an npm package?

When we "require" non-local NodeJS modules, what does the slash in the module name signify? For instance: from the GitHub page of the ShellJS npm module (link: https://github.com/shelljs/shelljs#javascript) require('shelljs/global'); requir ...