Struggling with consolidating values in an array of objects - seeking assistance with Javascript

Currently, I am handling a project where I receive data in the form of an Object Array. My task is to merge values with the same key into one key and convert the values into an array of strings.

Below is the sample data I am working with:

 inputArray = [
    {
      colors: 'Red',
      size: 'Small'
    },
    {
      colors: 'Blue',
      size: 'Large'
    },
    {
      colors: 'Red',
      size: 'Large'
    },
    {
      colors: 'Pink',
      size: 'X-Large'
    }
  ]

Here is the desired output :

 outputArray = {
    colors: ['Red','Blue','Pink'],
    size: ['Large','X-Large','Small']
  }

Answer №1

To achieve this, you can utilize a basic dictionary structure. It is important to check if each element already exists before adding it to the array.

const resultArray = {
  colors: [],
  size: [],
};

for (element of inputData) {
  if (!resultArray['colors'].includes(element.colors)) {
    resultArray['colors'].push(element.colors);
  }

  if (!resultArray['size'].includes(element.size)) {
    resultArray['size'].push(element.size);
  }
}

This will result in

{
   colors: [ 'Red', 'Blue', 'Pink' ],
   size: [ 'Small', 'Large', 'X-Large' ]
}

Answer №2

It's a simple solution...

const inputArray = 
  [ { genre: 'Action',  rating: 'PG-13'  } 
  , { genre: 'Drama', rating: 'R'  } 
  , { genre: 'Fantasy',  rating: 'PG-13'  } 
  , { genre: 'Sci-Fi', rating: 'G'} 
  ];
outputArray = inputArray.reduce((a,c)=>
  {
  if (!a.genre.includes(c.genre) )  a.genre.push( c.genre);
  if (!a.rating.includes(c.rating) )      a.rating.push( c.rating);
  return a
  }
  ,{ genre:[], rating:[]})
  ;
console.log (outputArray )

[edit] If you are unsure about the types of input keys, you can use:

inputArray = 
  [ { genre: 'Action',  rating: 'PG-13'  } 
  , { genre: 'Drama', rating: 'R'  } 
  , { genre: 'Fantasy',  rating: 'PG-13'  } 
  , { genre: 'Sci-Fi', rating: 'G', extra: 'info' } 
  ];
outputArray = inputArray.reduce((a,c)=>
  {
  for (let key in c)
    {
    if (!a[key]) a[key] = []
    if (!a[key].includes(c.genre) )  a[key].push( c[key])
    }
  return a
  } ,{})
  ;
console.log (outputArray)

Answer №3

It appears to be functioning...

let data = [
    {
      color: 'Green',
      size: 'Medium'
    },
    {
      color: 'Purple',
      size: 'Small'
    },
    {
        color: 'Blue',
        size: 'Medium'
    },
    {
        color: 'Yellow',
        size: 'Large'
    }
]

let result = [{color: [], size: []}]
for (let i = 0; i<data.length; i++){
  result[0].color.push(data[i].color)
  result[0].size.push(data[i].size)
}
console.log(result)

Does this meet your expectations?

Answer №4

Although similar to the second part of Mister Jojo's answer, this approach achieves the same result without any mutations, potentially making it more functional:

const groupBy = (items) =>
  items.reduce(
    (acc, item) => Object.entries(item).reduce((acc, [key, value]) => ({...acc, [key]: (acc[key] || []).concat(value)}), acc),
    {}
  )

const dataArray = [{ colors: 'Red', size: 'Small'}, { colors: 'Blue', size: 'Large'}, { colors: 'Red', size: 'Large'}, { colors: 'Pink', size: 'X-Large'}]

console.log(groupBy(dataArray))

Although possibly less efficient than the aforementioned version, as explained by Rich Snapp, in practice, this has not proved to be a significant issue.

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

Ways to navigate through textarea components within an iframe tag

I am presented with the following HTML structure: <iframe id="screenshare" ref="screenshare" class="fullScreen2"></iframe> To dynamically fill the <iframe> element, I am utilizing JavaScript through the below function: func ...

The correct method for concealing components from unauthorized users in Vue

After much thought, I'm considering transitioning my app entirely to Vue frontend. However, there are some concerns on my mind, such as: Currently, in Laravel blade (posts page), I have the following structure: @foreach($posts as $post) <post dat ...

Unveiling the Ultimate Method to Package Angular 2 Application using SystemJS and SystemJS-Builder

I'm currently in the process of developing an application and I am faced with a challenge of optimizing the performance of Angular 2 by improving the loading speed of all the scripts. However, I have encountered an error that is hindering my progress: ...

Installing Eclipse for PHP and JavaScript on your computer is a simple process. Here

Currently, I am working on a web project that consists mostly of PHP and JavaScript files, as well as some HTML and CSS files. I have decided to use Eclipse as my Integrated Development Environment (IDE) for this project. However, upon visiting eclipse.org ...

Vue.js data does not exhibit reactivity

I am encountering an issue with a non-reactive data object nested inside another object in my Vue.js template. Here is the code snippet: <template> <div> <b-container class="bg-white text-center scrollBehavior" > ...

Playing with Data in AG-Grid using Javascript

I am working on implementing data display using AG Grid with an AJAX call, but I am facing an issue where no data is being shown in the grid. Even though my AJAX call seems to be functioning correctly and returning the desired object List, the grid itsel ...

How can I configure AngularJS intellisense in Visual Studio Code?

I've been customizing Visual Studio Code for better compatibility with our Angular 1.5 codebase at my workplace. Here's the progress I've made so far: Downloaded and installed TSD Ran the command tsd query -r -o -a install angular -s Added ...

When the enter key is pressed, scope.$watch() does not trigger, and location.path does not function as expected

I've encountered a peculiar problem with AngularJS that I need help with. Here's the situation: Using scope.watch to monitor text changes in a text field (searchloco). <input class="typeahead" ng-model="searchloco" data="{{varu}}" search-ba ...

The function Router.use is looking for a middleware function, but instead received an object in node.js /

I encountered an issue while trying to setup routing in my application. Whenever I attempt to initialize a route using app.use() from my routes directory, I receive an error stating that Router.use() requires a middleware function but received an Object in ...

The continuous re-rendering is being triggered by the Async/Await Function

I am facing an issue with fetching data from the backend using axios. The function is returning a Promise and each time I call it, my component keeps rendering continuously. Below is the code snippet: import { useState } from "react"; import Ax ...

How to display the compilation date in npm

During npm run watch is running in the background, I can see a recompilation process every time I make a change to the jsx code. Is there a way for npm to display the last time a jsx file was compiled? Thank you ...

Having trouble with a lengthy formula in your Google Sheets Apps Script function? You may encounter an error like `SyntaxError: missing ) after argument list line: 14 file: new line.gs`. Let

The Apps Script function being discussed: function insertNewRow() { var ss = SpreadsheetApp.openById("redactedforprivacy"); var sheet = ss.getSheetByName("Main"); sheet.insertRowBefore(2); var date = new Date(); var month = date.getMonth() + 1 ...

tips for extracting data from a json array

Hello everyone, I have a question that I could use some help with. I have a set of data that looks like this: var data = { "values":[[1,2,3],[2,4,3],[3,6,7],[1,4],[6,4,3,4],[6,7,3,5]] } Currently, I am trying to create a multiple line chart usi ...

jQuery template does not respond to input text when a click event is enabled on an iPhone device

Below is a jQuery template I have: <div class="parent-class"> <div class="sub-class"> <div clas="sub-input-class"> <input type="text" /> </div> </div> </div> Recently, I ...

Unique text: "Singleton React component"

A counter component has been implemented using a npm package available here. import * as React from 'react'; import { Theme, createStyles, withStyles, WithStyles } from '@material-ui/core'; import withRoot from '../../../withRoot&a ...

Having trouble closing my toggle and experiencing issues with the transition not functioning properly

Within my Next.js project, I have successfully implemented a custom hook and component. The functionality works smoothly as each section opens independently without interfering with others, which is great. However, there are two issues that I am facing. Fi ...

Attempting to iterate over elements within an object labeled as strIngredients 1-15

event.preventDefault(); $('#mainContent').empty(); $.ajax({ url: randomDrinksURL, method: 'GET' }).then(function (response) { console.log(response); var mainContent = $('#mainContent&ap ...

The feature to prevent multiple selections in JSTree is not functioning as expected

Incorporating JSTree into my application involves the code below. this.CreateTreeView = function () { $('#jstree_demo_div').jstree({ 'core': { 'multiple': false, 'data': [ ...

Enhancing AngularJs code effectiveness through the use of MVC framework

I'm completely new to AngularJs and still trying to grasp the concepts. I have a few questions that I hope someone can help me with: Is it possible to trigger code in the controller only when a button is clicked, rather than having it load with the ...

Are toggle functionalities triggered when an element is clicked?

How come the span triggers functions a and b when first clicked, is there a way to set it up so that it calls function a on the first click and then function b on the second click? function a(id) { $.post("url.php", {'id':id}, function() { ...