What is the best way to merge the values of an array within an array of objects with the same property in JavaScript?

Check out the array below:

const a = [
  {
    26: [0],
    27: [100],
    28: [0]
  },
  {
    26: [0],
    27: [100],
    28: [0]
  },
  {
    26: [0],
    27: [100],
    28: [0]
  }
]

Is there a function available that can merge arrays with identical keys within an object?

`const result = [{
26: [0,0,0],
27: [100,100,100],
28: [0,0,0]
}]`

Answer №1

Consider utilizing the reduce method

const information = [{
    26: [0], 27: [100], 28: [0]
  },
  {
    26: [0], 27: [100], 28: [0]
  },
  {
    26: [0], 27: [100], 28: [0]
  }
];

const organizeData = arr => 
  [arr.reduce((accumulator, current) => {
    for (const [key, value] of Object.entries(current)) {
      accumulator[key] = [...accumulator[key] ?? '', ...value];
    }
    return accumulator;
  }, {})];

console.log(JSON.stringify(organizeData(information)));

Answer №2

To achieve this task, you can make use of the Array.forEach() method in JavaScript.

Here is a simple demonstration:

const data = [{
  26: [0],
  27: [100],
  28: [0]
}, {
  26: [0],
  27: [100],
  28: [0]
}, {
  26: [0],
  27: [100],
  28: [0]
}];

let resultObject = {};

data.forEach(item => {
    Object.keys(item).forEach(key => {
    resultObject[key] ? resultObject[key].push(...item[key]) : resultObject[key] = [...item[key]]
  })
});

console.log([resultObject]);

Answer №3

Having a set of utility functions on hand can greatly simplify tackling this type of problem.

The approach I take is to create the following function:

const combine = reduce (mergeWith (concat)) ({}) 

This function is built using my utility functions reduce, concat, and mergeWith. Using it is as straightforward as:

combine (a) //=> {26: [0, 0, 0], 27: [100, 100, 100], 28: [0, 0, 0]}

const reduce = (f) => (init) => (xs) => xs .reduce ((a, x) => f (a, x), init)
const concat = (a) => (b) => a .concat (b)
const mergeWith = (f) => (a, b) => Object .fromEntries (
  [... new Set ([... Object .keys (a), ... Object .keys (b)])] .map (
    (k) => [k, k in a ? (k in b ? f (a [k]) (b [k]) : a [k]) : b [k]]
  )
)

const combine = reduce (mergeWith (concat)) ({}) 

const a = [{26: [0], 27: [100], 28: [0]}, {26: [0], 27: [100], 28: [0]}, {26: [0], 27: [100], 28: [0]}]

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

reduce and concat essentially convert array methods into pure functions.1 They are fully curried, making it easier to compose functions by calling them with multiple arguments instead of using method chaining.

mergeWith function performs a shallow merge between two objects, utilizing a provided function when keys match in both objects, and using the supplied property otherwise.

By setting up these utility functions in advance, writing the solution becomes quite straightforward. We configure mergeWith with concat and pass them along with an empty object to reduce.

const combine = reduce (mergeWith (concat)) ({})

1reduce does not provide all parameters to the transformation function that Array.prototype.reduce does. This design choice has its reasons, but if desired, we could simplify the implementation to

const reduce (f) => (init) => (xs) => xs .reduce (f, init)
.

Answer №4

One way to accomplish this task is by utilizing the built-in Array.Prototype.map() method in JavaScript.

Here is a sample solution:

function mergeSameKeys(arr) {
    let filteredObj = {}

    arr.map(obj => {
        let objKeys = Object.keys(obj);

        objKeys.map(key => {
            if (!filteredObj.hasOwnProperty(key)) {
                filteredObj[key] = obj[key]
            } else {
                filteredObj[key].push(...obj[key])
            }
        })

    })

    return [filteredObj]
}

mergeSameKeys([{
    26: [0],
    27: [100],
    28: [0]
  },
  {
    26: [0],
    27: [100],
    28: [0]
  },
  {
    26: [0],
    27: [100],
    28: [0]
  }
])

// returns [{
// 26: [0,0,0],
// 27: [100,100,100],
// 28: [0,0,0]
// }]

The above function iterates through each item in the given array. For each object, it extracts all the keys using Object.keys(), storing them in objKeys. It then loops through each key in objKeys and checks if that key already exists in the filteredObj variable. If not, it adds the key along with its value to filteredObj. If the key is present, it merges the values from the original object and the filteredObj using the Spread syntax (...). The function ultimately returns the filteredObj in an array. This completes the code implementation.

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

Issues with Javascript FadeToggle functionality not behaving as expected

When I click the reply button, the reply form opens. However, it has a problem where the code only works for the first element https://i.sstatic.net/Zoet4.png After that https://i.sstatic.net/Hotsq.png Button code <div class="reply-button bubble-orn ...

Jquery function for determining height across multiple browsers

I am currently facing an issue with setting the height of table cells in my project. While everything works smoothly on most browsers, Firefox seems to add borders to the overall height which is causing inconsistency across different browsers. If anyone k ...

Sending a form without the need to reload the page

While it's known that Ajax is the preferred method to submit a form without refreshing the page, going through each field and constructing the Post string can be time-consuming. Is there an alternative approach that utilizes the browser's built-i ...

Unspecified locale with Next.js router

Despite extensive research and multiple attempts, I have not been able to find a solution to my problem. That's why I am reaching out for help again. Currently, I am working on a local project and I would like to implement Internationalized Routing f ...

Verifying Value Equality in all Documents with MongoDB

One feature on my website allows users to input a number into the field labeled subNum in a form. Upon submission of the form, I need to validate whether the entered value already exists within any existing document. This validation process is implemented ...

Dealing with XMLHttpRequest timeout issues in a React.js application

Within my react.js project, I have a function named getData in the Profile class. Here is how it appears: getData() { console.log("inside get data"); var request = new XMLHttpRequest(); request.timeout=1000; request.ontimeout=function () { ...

Editing input within a Bootstrap 4 popover causes it to lose focus

I am using Bootstrap 4 along with the Bootstrap colorpicker to implement a colorpicker within a popup that includes an input field for setting the color code. However, I am facing an issue where the input field (#color-value) seems uneditable when the popo ...

Retrieve data using ajax within an mvc framework

I am facing an issue where I am unable to receive the data sent with AJAX jQuery to a .NET server as a parameter, modify it in memory, and then convert it to JSON. Any assistance in resolving this problem would be greatly appreciated. JAVASCRIPT document ...

Divide a PHP array into two separate arrays

Given an array with 3 elements as shown below, the task at hand is to split these elements into two separate arrays based on the value of the pay_flag key: One array should only contain entries where pay_flag is set to 0, while the other array should incl ...

Understanding JavaScript Prototypal Inheritance within ES5 Classes

I've been working on creating an XMLHttpRequest interceptor for Angular, encountering a roadblock when trying to intercept a third-party library that uses the XMLHttpRequest API. Although the solution below is functional, I've run into issues wit ...

What are the steps to incorporate swipe functionality into my component?

I've created a carousel using React-slideshow-image, but the issue is that it doesn't support swiping on mobile devices. I would like to implement swipe functionality myself, but I'm not sure how to go about it. Can anyone provide guidance ...

Try utilizing a distinct value for searching compared to the one that is shown in Material UI's Autocomplete feature for React in JavaScript

I'm currently utilizing the <AutoComplete /> component offered by Material UI. It prescribes the following organization for the options const options = [ { label: 'The Godfather', id: 1 }, { label: 'Pulp Fiction', id: 2 } ...

Error message 'AVV_ERR_PLUGIN_NOT_VALID' encountered within fastify

I've encountered an issue while setting up the environmental variables in my fastify - react app. Can someone help me with resolving the 'AVV_ERR_PLUGIN_NOT_VALID' error that I'm receiving for the following fastify code? Your assistance ...

What drawbacks come with developing an Express.js application using TypeScript?

Curious about the potential drawbacks of using TypeScript to write Express.js applications or APIs instead of JavaScript. ...

Updating records in MySQL using jQuery and PHP through an inline method

I'm using JQuery/Ajax and php/MySQL to perform CRUD operations. Currently, I can insert/select and delete data without any issues. However, I'm facing a challenge with the edit/update functionality. When I try to edit data and click on the save ...

Utilizing a button's "data-" attribute to trigger a specific JavaScript function

I am trying to assign data to my buttons in a way that makes it accessible when clicked. While I can easily use JSON in a button's data attribute with a string as the key value, I am struggling to set the values to be a function instead. What I want ...

What is the best way to keep vue-meta up to date when the route or URL

The issue I am facing is that the meta data on my website does not update when the route changes. Even though the route has a watch function that updates the view correctly, the metaInfo() method from vue-meta fails to keep up with the changes. Below is an ...

Implementing Vue.js functionality to dynamically add or remove values from an array based on the state of a checkbox

I recently embarked on my journey to learn vue.js and I've encountered a challenging issue. I have dynamic data that I render using a 'v-for' loop. Additionally, I have an empty array where I need to store checked checkbox data and remove it ...

Each time I refresh the page, the user data disappears and I have to login

Hello there, I am currently utilizing Express for backend authentication and these are the sign in functions/controllers implemented on the front end. export const signInUser = async credentials => { console.log('this is for the signInUser&apos ...

Connecting to a specific mui-tab with react-router-dom

How can I link to a specific tab in my material ui-based tabs setup within a React application? I want to be able to navigate directly to a particular tab when landing on the page, but I'm struggling with integrating this functionality. Is there a way ...