Combining two arrays with identical IDs using Angular or JavaScript - a step-by-step guide

As a newcomer to Angular and JavaScript, I am attempting to combine values with the same ID into one row using concatenation.

var array = [{
            id: "410",
            value: "val1"
        }, {
            id: "411",
            value: "val1"
        }, {
            id: "412",
            value: "val4"
        },{
            id: "410",
            value: "val2"];

            var output = [];

I hope for the desired output to look like this:

output = [
{id:"410", value:["val1","val2"]},
{id:"411", value:["val1"]},
{"id":412,value:["val4"]}]

Any assistance on achieving this would be greatly appreciated. Thank you in advance.

Answer №1

Please ensure that your value attribute is formatted as an array.

To achieve the desired result, consider utilizing the reduce function.

var array = [{ id: "410", value: "val1" }, 
             { id: "411", value: "val1" }, 
             { id: "412", value: "val4" }, 
             { id: "410", value: "val2"}];

var output = array.reduce((a, c) => {
  var id = c.id;
  var e = a.filter((e) => e.id == id)[0];
  if (e) {
    e.value.push(c.value);
  } else {
    a = [...a, ...[{ id: id, value: [c.value] }]];
  }
  
  return a;
}, []);

console.log(output);

Resource

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

Issue with Ajax/Json: "An object of type triggers a circular reference error when attempting to retrieve a list."

Recently, I encountered an issue with my server-side method that is triggered through JSON/Ajax. The method itself functions flawlessly and sends back a list as expected. However, I seem to have made an error in my JavaScript code, leading to the following ...

Altering the properties of every item within a v-for loop's array

I'm currently exploring Vue's approach to writing JavaScript. Let's consider this situation: In the .vue template <button v-on:click="biggerFont()" class="btn btn-s btn-default" type="button" name="button">A</button> < ...

jQuery does not pass data to bootstrap modal

I am currently working with the full calendar feature. Within this framework, I have implemented a modal that allows users to insert new events: <div id="fullCalModal_add_appointment" class="modal fade"> <div class="modal-dialog"> ...

Having trouble getting Emberjs to properly handle an Ajax POST request

Currently, my goal is to send data to the database using Ajax POST. To start off, I have an HTML form as follows: <script type="text/x-handlebars" id="project"> <div class="row"> <div class="span6"> <form class ...

What is the best way to update a form without refreshing the DOM?

Is it possible to update a form with user-modified data without reloading the DOM when someone clicks the submit button? My app currently works perfectly but only updates the form when the DOM is reloaded. Server Code: "use strict"; // Server code here ...

Invoke a PHP function located in a separate file using a JavaScript function to fetch data from a database

How can I properly call a PHP function from a JavaScript function located in a different file? I am trying to pass a variable from an onClick function in JavaScript to a PHP function, which will then access a MySQL database to retrieve data. However, my c ...

Performing queries using the ORM Sequelize to fetch data from two separate tables simultaneously during a single page

I have encountered a challenge while working on my project. I need to display data from two different tables on one page (page.hbs). My tech stack includes Node.js ORM Sequelize, MySQL database, and Handlebars for templating. However, I am facing difficult ...

Error message: Unknown scope- unable to process 'files-path' Android File provider issue

My current project involves implementing file system access in react native Android. However, when attempting to add 'files-path' in XML, an error stating "Error: Unsupported type 'files-path'" is encountered. I am utilizing the react n ...

Utilizing Reactjs to dynamically populate Bootstrap grids: A step-by-step guide

Is there a more efficient way to display match stats boxes using ReactJS and Bootstrap grids? I currently have 16 grids set up in a 4X4 layout, each row containing 4 columns. Instead of manually creating 16 match stats boxes, is there a way to dynamically ...

AngularJS UI-Router homepage route

I have been using the ui-router plugin in my AngularJS project, which can be found at https://github.com/angular-ui/ui-router. Below is a snippet of the code I am working with: $stateProvider.state('home', { url: '', ...

Typescript headaches: Conflicting property types with restrictions

Currently, I am in the process of familiarizing myself with Typescript through its application in a validation library that I am constructing. types.ts export type Value = string | boolean | number | null | undefined; export type ExceptionResult = { _ ...

Find the current elapsed time using Wavesurfer in real time

I am currently utilizing the waveSurfer library created by katspaugh for playing audio files. In order to display 'elapsed time / total time', I have written code in the following manner: waveSurfer.on('play', function() { $scope.g ...

`"Error: posts.map is not a function" - What steps can be taken to resolve this issue?`

While working on fetching data from my local Drupal instance in React JS, I encountered a situation where I needed to pass the data from Drupal using the JSON API module which sends the data in JSON format. You can view the JSON API data in the following i ...

Looking to display several charts on a single page with varying datasets?

I have successfully integrated a doughnut chart plugin into my website. However, I would like to display multiple charts on the same page with different data sets. Below is the code snippet for the current chart being used: This is the chart I am using & ...

How can TypeScript objects be serialized?

Is there a reliable method for preserving type information during JSON serialization/deserialization of Typescript objects? The straightforward JSON.parse(JSON.stringify) approach has proven to have several limitations. Are there more effective ad-hoc sol ...

Using data-image as the source for Bootstrap Modal

I am currently working on an image gallery that utilizes the Paver jQuery plugin. The gallery is functional, but I am facing an issue where it displays the same image in the modal instead of showing the respective data-image for each image. My goal is to ...

Changing a string into an array through an ajax request using javascript

After making an ajax call, I received a result from an array that looks like result = [one, two, three]; However, I encountered an issue where I need to convert this into a valid array in order to iterate it properly. The problem arises because my string ...

Creating Hbbtv applications with the help of a Firefox Addon

My curiosity lies in creating hbbtv apps and I am eager to learn how to run and test a complete hbbtv application package, specifically a videoplayer with multiple html pages, utilizing the FireHBBTV plugin on Firefox. Despite my extensive search efforts ...

React Native (or React) utilizes separate TypeScript modules to detect and respond to style adjustments for dark mode

Objective: Add a dark mode feature to a react native application. A brief overview of the system: File structure: Profile.ts ProfileCss.ts constants.ts In my app, I've organized styles in separate .ts files and exported them as modules to keep them ...

What is the best way to modify an element's state based on the index array?

Here is the current state object: state = { index: 0, routes: [ { key: 'first', title: 'Drop-Off', selected: true }, { key: 'second', title: 'Pick up', selected: false }, ], }; I want to ...