Categorize an array by shared values

Here is an example of my array structure:

myArray = [
  {SKU: "Hoo12", Name: "ACyrlic watch",OrderNo:"26423764233456"},
  {SKU: "S0002", Name: "Princes Geometry",OrderNo:"124963805662313"},
  {SKU: "Hoo12", Name: "ACyrlic watch",OrderNo:"122324234234"},
]


I am trying to convert the array to the following format:

OutPut = [
  {SKU: "Hoo12",Name: "ACyrlic watch", OrderNo: ["26423764233456", "122324234234"]},
  {SKU: "S0002", Name: "Princes Geometry", OrderNo: ["124963805662313"]}
]

I have experimented with different methods, but I am struggling to group similar values together.

Answer №1

When you encounter data that requires grouping, Array.reduce is a powerful tool.

For example:

const myArray = [
  {SKU: "Hoo12", Name: "ACyrlic watch",OrderNo:"26423764233456"},
  {SKU: "S0002", Name: "Princes Geometry",OrderNo:"124963805662313"},
  {SKU: "Hoo12", Name: "ACyrlic watch",OrderNo:"122324234234"},
];

const OutPut = myArray.reduce((a,v) => {
  let c = a.find(f => f.SKU === v.SKU);
  //check if SKU already exists
  if (!c) {
    //If not, add it
    c = v;
    c.OrderNo = [v.OrderNo];
    a.push(c);
  } else {
    //If yes, add the OrderNo
    c.OrderNo.push(v.OrderNo);
  }
  return a;
}, []);

console.log(OutPut);

Answer №2

With the use of the `reduce` method, you can easily obtain the desired output

const myArray = [ {SKU: "Hoo12", Name: "ACyrlic watch",OrderNo:"26423764233456"}, {SKU: "S0002", Name: "Princes Geometry",OrderNo:"124963805662313"}, {SKU: "Hoo12", Name: "ACyrlic watch",OrderNo:"122324234234"}];

const result = Object.values(myArray.reduce((a,{OrderNo, ...r})=>{
    a[r.SKU] ??= {...r, OrderNo:[]};
    a[r.SKU].OrderNo.push(OrderNo)
    return a;
},{}));

console.log(result);

Answer №3

If you prefer not to alter the original myArray in a pure function, a straightforward forEach loop can work.

// Initialization
myArray = [
  {SKU: "Hoo12", Name: "ACyrlic watch",OrderNo:"26423764233456"},
  {SKU: "S0002", Name: "Princes Geometry",OrderNo:"122324234234"},
  {SKU: "Hoo12", Name: "ACyrlic watch",OrderNo:"122324234234"},
]

OutPut = []

// Loop through each element of the array
myArray.forEach(elem => {
  // Check if there is a matching SKU and Name in the output array
  let found = OutPut.find(o => o.SKU == elem.SKU && o.Name == elem.Name)
  // If found, add the OrderNo to the existing array
  if (found) {
    found.OrderNo.push(elem.OrderNo)
  }
  // If not found, create a new object with OrderNo as an array
  else {
    OutPut.push({ SKU: elem.SKU, Name: elem.Name, OrderNo: [ elem.OrderNo ] })
  }
})

// Display the output
let c = document.createElement('pre');
c.innerText = JSON.stringify(OutPut, null, 2)
document.body.appendChild(c)

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 show distinct items and their frequencies from an array of objects in Vue.js/JavaScript?

I have been developing an inventory management application using Vuejs, and I am facing a JavaScript-related challenge in my project. The issue revolves around handling data that includes user information retrieved from a form, as well as static categories ...

Node.js course utilizing MySQL library implementing Object-Oriented Programming concepts

Learning to work with MySQL in Node has been quite challenging for me. I am using the npm package 'mysql' for my project. I am aiming to follow OOP principles by creating an independent class to handle all my DB requests. However, I am facing an ...

The switch statement remains unchanged for varying variables

Here is some code that I am working with: updateTable(selectedIndex) { console.log("running updateTable function"); let level = ''; // if (selectedIndex == 1){ // this.setState({level: 'day'}) // th ...

I am experiencing issues with the jQuery function within my MVC Application

When working on my MVC application, I encountered an issue where the onclick function was not functioning as expected. @section Scripts{ <script src="~/Scripts/plugins/toastr/toastr.min.js"></script> <script> $(document). ...

JavaScript Drag-and-Drop Statement Issues

Currently working on a JavaScript game that utilizes the drag and drop feature of HTML. The goal is to make randomly generated fruit images draggable and droppable onto a jelly image. When the dragged image matches a certain condition (e.g., when the numbe ...

Form elements change when focused on text boxes

I am attempting to replicate the materialize style for input boxes where the label moves up and decreases in font size with animation when the text box is clicked. Although I have managed to achieve this effect, there seems to be a slight issue. When clic ...

Integrate several YouTube players within a tabbed angular-ui system. Looking to incorporate a collapse feature

I come to you with a humble request for guidance. As a newcomer to Angular and someone who has never ventured into the realm of the YouTube JavaScript API, I am well aware that I may be making errors without even realizing it. While my code appears to be f ...

Error message: NGINX combined with Express.js and socket.io, page not found

I currently have a node/express.js/socket.io application set up on an Ubuntu Server running on port 3002. I've made sure to open all ports on the machine for accessibility. When accessing the app directly at 11.111.111.1:3002/, everything runs smooth ...

The share-modal.js file is throwing an error because it is unable to read properties of null, particularly the 'addEventListener' property, at

I encountered an error that I want to resolve, but it's proving to be quite challenging. Despite extensive searching on Google, I haven't found a solution yet. Uncaught TypeError: Cannot read properties of null (reading 'addEventListener&apo ...

Concealing the sidebar in React with the help of Ant Design

I want to create a sidebar that can be hidden by clicking an icon in the navigation bar without using classes. Although I may be approaching this incorrectly, I prefer to keep it simple. The error message I encountered is: (property) collapsed: boolean ...

In JavaScript, efficiently remove specific node types from a tree structure using recursion, while also maintaining and distributing qualified child nodes

Currently, I am working on a recursive function that operates on a JSON tree structure {name, type, [children]}, with the goal of removing nodes of a specific type. However, it is essential that the children of the removed node are reattached to the parent ...

Transform JSON into a JavaScript array object using node.js

My knowledge of Javascript is limited and I need assistance with a .json file that has the following structure: { "results": [ { "challenger": { "__type": "Pointer", "className": "Player", "objectId": "STWAxAHKay" }, "c ...

Sync user information when alterations are made on a different device

As I create a Discord clone using Next.js, I've encountered an issue where when a server is deleted, another client can still see and use the server until the page is reloaded. When testing out the official Discord web app, changes seemed to happen in ...

What happens in the React tutorial when the clear fix is commented out and the appearance does not change?

Currently, I am working through the React tutorial and have encountered a question regarding their starter code: class Square extends React.Component { render() { return ( <button className="square"> {/* TODO */} </butto ...

Establishing Accessor and Mutator Methods

The variables startStopA... and InitialValueA... that were originally in the component TableFields.vue need to be relocated to the store file index.js. However, upon moving them to the store, an error appears stating that setters are not set. I have extens ...

How to Retrieve Superclass Fields in Angular 5 Component

I have a superclass that provides common functionality for components. export class AbstractComponent implements OnInit { public user: User; constructor(public http: HttpClient) { } ngOnInit(): void { this.http.get<User>(& ...

Implementing route prefix in a combination of express and react deployment

I'm currently facing a challenge while trying to deploy a react app that utilizes router functionality with express. The react app is expected to be accessible via the /dashboard route. At first glance, everything seems to be working smoothly on the ...

Exploring the concept of template inheritance in Vue.js

Is there a way to implement template inheritance similar to Jade’s extends file.jade? I understand that composition can achieve the same result, but for components like the footer and header which are present on most pages except a few (e.g. login page), ...

AJAX request is successful, however, the database remains empty with no data being inserted

I have been attempting to utilize ajax and php to insert data into a database, but for some reason, it is not functioning as expected. Despite validating all the itemName, category, and price fields in the html file, the data being inserted into the data ...

Tips for organizing date columns in Bootstrap-Vue when utilizing a formatter for presentation purposes

I am working with a table containing date objects, and I have transformed them for display using the following code: { key: "date", formatter: (value, key, item) => { return moment(value).format("L"); }, sortable: true } However, this ...