javascript multiple arrays that can be reduced or summed up together

What is the most efficient method for reducing this array?

data = {
    id: [1, 1, 1, 3, 3, 4, 5, 5, 5, ...]
    v: [10,10,10, 5, 10 ...]
}

Each id has a corresponding value in v. The goal is to sum up the values of v for each id. Based on the example provided, the desired result would be:

data = {
    id: [1, 3, 4, 5, ...]
    v: [30, 15, ...]
}

Answer №1

My recommendation would be to utilize the Array.prototype.reduce() method as it offers a simple and elegant solution.

var ids = [1, 1, 1, 3, 3, 3, 3, 4, 5, 6, 6, 6],
  v = [10, 10, 10, 5, 10, 10, 10, 404, 505, 600, 60, 6],
  data = {};
data.v = [];
data.ids = ids.reduce(function(a, b, index) {
  if (a.indexOf(b) < 0) a.push(b);
  if (!data.v[a.indexOf(b)]) data.v[a.indexOf(b)] = 0;
  data.v[a.indexOf(b)] += v[index];
  return a;
}, []);

Head over to this JSFiddle link for more details!

Answer №2

To achieve this with two arrays of the same length, you can utilize mapping and reducing:

const ids = [1, 1, 1, 3, 3];
const vs = [10,10,10,5,10];

const reduced = ids
.map((val, i) => ({ id: val, value: vs[i] }))
.reduce((agg, next) => {
    agg[next.id] = (agg[next.id] || 0) + next.value;
    return agg;
}, {});

console.log(reduced);

// Object {1: 30, 3: 15}

Here's a live demonstration: https://jsfiddle.net/h1o5rker/1/

Answer №3

I believe this task can be achieved using the reduce method.

 var data = {
   id: [1, 1, 1, 3, 3],
   v: [10, 10, 10, 5, 10]
 }

 var sumsObjs = data.v.reduce(function(sum, val, index) {
   var id = data.id[index];
   if (sum[id] !== undefined) {
     sum[id] = sum[id] + val;
   } else {
     sum[id] = val;
   }
   return sum;
 }, {});

 console.log(sumsObjs);
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>

Answer №4

let data = {
  id: [1, 1, 1, 10, 123, 4531],
  v: [123, 123, 53, 223, 11, 11, 11]
};
let _v = data.v;
let vinit;

document.write(data.v + '<br>');
for (let i = 0; i < _v.length; i++) {
  vinit = _v[i];
  for (let j = i + 1; j <= _v.length; j++) {
    if (_v[j] === vinit) {
      delete _v[j];
    }
  }
}

document.write(data.v);

let data = {
  id: [1, 1, 1, 10, 123, 4531],
  v: [123, 123, 53, 223, 11, 11, 11,...]
};
let _v = data.v;
let vinit;
for (let i = 0; i < _v.length; i++) {
  vinit = _v[i];
  for (let j = i + 1; j <= _v.length; j++) {
    if (_v[j] === vinit) {
      delete _v[j];
    }
  }
}

The provided code snippet focuses on reducing repeating elements in array 'v', but similar implementation can be done for array 'id' as well by introducing additional variables.

In the code snippet, the presence of extra commas in the second line indicates the deletion of those specific elements.

Answer №5

If the IDs appear in consecutive order, a simple for loop can effectively handle the task without unnecessary complexity.

data = {
  id: [1, 1, 1, 3, 3, 4, 5, 5, 5],
  v: [10, 10, 10, 5, 10, 1, 2, 3, 4]
};

var result = {
  id: [],
  v: []
};

(function() {
  var ids = data.id,
    vals = data.v,
    lastId = ids[0],
    runningTotal = vals[0];
  for (var i = 1; i < ids.length; i++) {

    if (lastId === ids[i]) {
        runningTotal += vals[i];
    }

    if (lastId !== ids[i] || i + 1 === ids.length) {
      result.id.push(lastId);
      result.v.push(runningTotal);
      lastId = ids[i];
      runningTotal = vals[i];
    }
  }

}());

console.log(result);

Answer №6

Several solutions have been shared by different individuals, but none seem to precisely match your requirements. I would like to offer a solution that specifically caters to your needs and simplifies the object while maintaining its original format.

// Your current data object
data = {
    id: [1, 1, 1, 3, 3],
    v: [10,10,10, 5, 10]
}

// Function to reduce the object based on 'id' and 'v'
function simplify(obj){
  // Initializing the reduced object structure
  var simplifiedObj = {
    id: [],
    v: []
  }

  // Creating a hash map to store keys and values
  var map = {};
  for(var i=0; i<obj.id.length; ++i){
    // Check if key exists in the map, if not create it with value 0
    if(typeof map[parseInt(obj.id[i])] === 'undefined'){
      map[parseInt(obj.id[i])] = 0;
    }
    // Summing values for each key
    map[parseInt(obj.id[i])] += parseInt(obj.v[i]);
  }

  // Mapping the hash map back to the reduced object
  for(var ele in map){
    simplifiedObj.id.push(ele);
    simplifiedObj.v.push(map[ele]);
  }

  // Return the simplified object
  return simplifiedObj;
}

var mySimplifiedObject = simplify(data);
console.log(mySimplifiedObject);

View Working Fiddle

Answer №7

This code provides a solution for organizing IDs using Array.prototype.reduce().

var data = {
        id: [1, 1, 1, 3, 3, 4, 5, 5, 5],
        v: [10, 10, 10, 5, 10, 7, 8, 10, 13]
    },
    result = { id: [], v: [] };

data.id.reduce(function (r, a, i) {
    if (r === a) {
        result.v[result.v.length - 1] += data.v[i];
    } else {
        result.id.push(a);
        result.v.push(data.v[i]);
    }
    return a;
}, -1);
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

Alternatively, there is an in-place version of the solution.

var data = {
    id: [1, 1, 1, 3, 3, 4, 5, 5, 5],
    v: [10, 10, 10, 5, 10, 7, 8, 10, 13]
};

void function (d) {
    var i = 1;
    while (i < d.id.length) {
        if (d.id[i - 1] === d.id[i]) {
            d.id.splice(i, 1);
            d.v[i - 1] += d.v.splice(i, 1)[0];
            continue;
        }
        i++;
    }
}(data);

document.write('<pre>' + JSON.stringify(data, 0, 4) + '</pre>');

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

Is there a way to create a recurring Promise .then statement?

Is there a way to create a loop with a repeated .then clause? I need to continue executing the .then clause promise, and if the exit condition is not met, I have to repeat the same process until the condition is satisfied. My scenario involves making mult ...

next.js users may encounter a problem with react-table not rendering correctly

Encountering difficulties while attempting to integrate a basic table function into my upcoming application. Despite being a sample output, the function fails to load into the index for some unknown reason! // Layouts import Layout from "../components ...

Is there a way to automatically remove a document in MongoDB and Node.js once its expiration date has passed?

I'm working on an appointment booking app and I need to automatically delete booking details after the booked date has passed. How can I make this happen? I attempted to use node-scheduler for this task, but it wasn't successful. The app itself ...

Size attribute set to 0 for an HTML input element

When an input element is rendered, it should have a width of 0. However, when there is no text in the input, the width should remain 0. To achieve this, you can use the following jQuery code: $('input').on('input', function () { $(th ...

Creating dynamic image carousels using the latest versions of Bootstrap and AngularJS

I have created an array that stores various images using angularJS: $scope.docImg = [ '../../Content/Image/BackGrounds/abra.png', '../../Content/Image/BackGrounds/background_black.jpg', '../../Content/I ...

Including the file path to an image in a CSS module within a React component from the public directory

I'm currently facing a challenge with adding an image as a background, especially since the image is located in a public folder structure like this: -public -images -image.png -src -assets -components -index.tsx -index.module.css (I want to use the ...

Is file timestamp utilized by Apache to verify if a resource has been changed?

Currently, I am working on an HTML page that references a large JavaScript file (1MB+) that is rarely updated. According to this source, the JavaScript file will not be resent if it hasn't been modified. I'm curious about how Apache determines i ...

Utilizing a file from external sources in WebPack 1.x beyond the webpack root directory

In my project structure, I have the following setup: Root Project1 package.json webpack.config Project2 package.json webpack.config Common file1.js I need to use file1.js in each project. The webpack v ...

Detection of numerous Google Analytics tags

To troubleshoot a client's Google Analytics account connected to their website, I decided to utilize the Tag assistant by Google extension. Upon running it, an alert popped up displaying "Multiple Google Analytics tags detected." One tag was the one I ...

Error with Cross-Origin Resource Sharing (CORS) on my website

During the development of a website, I disabled web security in order to bypass CORS using the command chrome.exe --disable-web-security --user-data-dir=/path/to/foo However, after successfully completing the website and uploading it to my domain, I enco ...

Incorporating asynchronous file uploads to a server using a for loop

I am in the process of transforming my original code into "async" code. The initial code queries the database and retrieves the results, which includes images. I want to optimize writing the images asynchronously to my nodejs server as the current synchro ...

Reduce numerical values within tables

How can I shorten the numbers displayed on json / datatable? I have extracted json data from a website, but the figures shown in the json are too detailed. For instance, instead of displaying 408.43324032, I simply want to show 408 or 408x. https://i.ss ...

What is the best way to display or conceal buttons when the textarea is in focus or out of focus, while still allowing them

Seeking help to include two buttons beneath the input box. One button is for saving the input in the textarea, while the other is for aborting. The buttons should only be visible when the input field is focused. An issue I am facing is that clicking on ...

Click a button to adjust the height of an element

My webpage features a dashboard with tabs on the left and corresponding content on the right. To ensure proper alignment, I have utilized Bootstrap to create two columns - one for the tabs and one for the content. However, I am facing an issue where the bo ...

Obtain the milliseconds when utilizing the new Date().toLocaleTimeString() method

I was working on some code and came across this: v.d = new Date().toLocaleTimeString(); When I ran it, the output looked like this: 20:11:40 As you can see, this displays the time of day down to the second, without milliseconds. This made me wonder if ...

The required validator in Mongoose is not being triggered by the function

I'm trying to use a function as a validator in a mongoose schema, but it doesn't seem to work if I leave the field empty. The documentation states: Validators are not run on undefined values. The only exception is the required validator. You ...

What is the technique for defining sub paths in React-Router-Dom by excluding the parent path?

Imagine a Profile page that displays different components based on the path it receives. For example: /profile/posts will show the Posts component within Profile. /profile/comments will display the Comments component inside Profile. Typically, the Profi ...

retrieve the data-initial-value's value through JavaScript

Hello, I am currently attempting to retrieve the text from this input field but all I'm getting is an empty value. <input type="text" class="quantumWizTextinputPaperinputInput exportInput" jsname="YPqjbf" autocomplete= ...

Information provided in a login form does not carry over to a different page display

I'm currently facing a problem with my JavaScript code. I have constructed a login form and am attempting to transfer the data from the form to another page where it will be showcased in a table. Regrettably, the details are failing to appear on the s ...

Executing a personalized function within a Server Component with the Next JS App Router while the application is running

In my server component Home, I call the function getMyAge: // app/page.tsx import { getMyAge } from './utils/datetime'; export default function Home() { return ( <Page> <Paragraph>I'm {getMyAge()} years old</Parag ...