Merge the elements in an array using the items in JSON

I am struggling with extracting arrays from a simple array of JSON items. Here is the original data:

array = [
 {number: 9, item: 'Item 1', descripton: 'abc'},
 {number: 5, item: 'Item 2', descripton: 'def'},
 {number: 9, item: 'Item 2', descripton: 'ghi'},
 {number: 9, item: 'Item 1', descripton: 'xyz'},
]

My goal is to group items based on similar parameters ('number', 'item') and create a new array like below:

array = [
 [
  {number: 9, item: 'Item 1', descripton: 'abc'},
  {number: 9, item: 'Item 1', descripton: 'xyz'},
 ],
 [
  {number: 5, item: 'Item 2', descripton: 'def'},
 ],
 [
  {number: 9, item: 'Item 2', descripton: 'ghi'},
 ] 
]

I have attempted to use the .sort() and .filter() methods, but I have not been able to achieve the desired result.

Answer №1

let data = [
 {
  number: 9,
  item: 'Item A',
  descripton: 'abc'
 },
 {
  number: 5,
  item: 'Item B',
  descripton: 'def'
 },
 {
  number: 9,
  item: 'Item C',
  descripton: 'ghi'
 },
 {
  number: 9,
  item: 'Item A',
  descripton: 'xyz'
 },
];
data.sort((a, b) => {
      if (a.item > b.item) {
        return 1;
      } else {
        return -1;
      }
    });
    console.log(data);

When you execute the above JavaScript code, the output will be like this:
[
  { number: 9, item: 'Item A', description: 'xyz' },
  { number: 9, item: 'Item A', description: 'abc' },
  { number: 9, item: 'Item C', description: 'ghi' },
  { number: 5, item: 'Item B', description: 'def' }
]

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

Get every possible combination of a specified length without any repeated elements

Here is the input I am working with: interface Option{ name:string travelMode:string } const options:Option[] = [ { name:"john", travelMode:"bus" }, { name:"john", travelMode:"car" }, { name:"kevin", travelMode:"bus" ...

Changing from a vertical to horizontal menu as the parent div is resized

I am looking for a solution to create a CSS effect or Javascript code that will hide a menu inside a div when the browser window or parent div is resized. I want to display another div with the same menu in horizontal orientation when the first one is hidd ...

Leverage the JSON data retrieved from a URL within a Rails application

Currently, I am retrieving data from a website by utilizing its API key along with various parameters. The data is returned in the format of a JSON object. My concern now lies in effectively integrating this JSON object within my Rails application. Perha ...

I'm struggling with deleting a row from a pushed Object in Angular 2 and could use some guidance

Let me start by explaining my current issue: Initially, the problem was like this: , where it deleted the last created Object, Conditions in my case. However, I need to be able to delete each condition separately. For example, as shown with the red box n ...

Instructions for inserting a blank line between each JSONObject within a JSONArray, by utilizing json.simple and the Java programming language

I am currently attempting to save data to a JSON file using a JSONArray object from the json.simple library. However, I am encountering an issue with the formatting of the output file. At present, the format is as follows: [{"artist_name":"test1","year":0 ...

Utilize HarLib in Java to Retrieve Response Data

Has anyone had experience using HarLib with Java? I need to extract the "response" data from a .HAR file and display it on the screen. The getResponse() method in the HarEntry class seems to be the key, but I'm unsure about how to implement it based ...

Weekly downloads for NPM show no activity

https://i.stack.imgur.com/4Uhk4.png https://i.stack.imgur.com/0vikS.png Why are all the weekly downloads showing zero for npm packages? I'm new here and confused about why this is happening, any insights? If you could please help me open this issue ...

What causes the React white screen of death to disappear when this code is commented out?

Currently, I am working on a React application that pulls trivia questions and answers from an API to create a game interface. Everything has been going smoothly with the development process until I imported a decode function to properly display the trivi ...

Update the content of an image in a Div without altering its filename

My application's backend updates an image file and sends the filename back to the front-end: $('#giffinal').html(ResponseGo); However, when I update the image again through the backend, the code in the div on the front-end does not change. ...

Guide to generating an array entry for every line of a text file in node.js

Struggling with converting each line of a text file into an array entry in node.js The array I am working with is named "temp." The code below successfully prints out each line: var temp = []; const readline = require('readline'); const fs = re ...

Showcase an Array on an HTML page using EJS

When a user posts an object on my website forum using Ejs/NodeJs/MongoDb, it creates a new object with properties like title, comment, and reply array. I have successfully displayed the titles and comments in different HTML elements, but I am facing an i ...

"Troubleshooting: Ajax File Uploader Plugin Not Functioning Properly

Today, our web site's file upload feature using the javascript plugin Simple-ajax-uploader suddenly stopped functioning (09/05/2019). The upload div/button is unresponsive when clicked. This issue is not limited to our site; even the official plugin ...

Encountering an issue: "req.validatonErrors" is throwing an error as it is not recognized as a function. The

Currently, I am a beginner and enrolled in a Udemy course to learn about node/express/mongo. However, I have hit a roadblock that is causing some difficulty for me. The issue seems to be related to the usage of express-validator in my form code. I suspect ...

Having trouble with .animate() function?

Struggling to animate the position of my background image $(function() { $('#nav1').bind('click',function(event){ $('ul.nav').stop().animate({backgroundPosition: 'right top'}, 1000); }); $(function() { ...

Troubleshooting a scope problem with ng-include while maintaining the original template

I have a select box within my template that has the following structure: <form name="myForm" class="fixed-select"> <select name="repeatSelect" id="repeatSelect" ng-model="selectedItem"> <option ng-repeat="program in pro ...

Display the flowplayer div when the anchor is clicked

I have a dynamic CGI page that displays a list of files. The number of files varies based on uploaded content, so I am looking to create previews for video files. Below is a snippet of HTML code: <TMPL_LOOP files> <tr> <td&g ...

Encountering an issue with receiving "undefined" values while utilizing WordPress post metadata in AngularJS

Utilizing the Wordpress REST API v2 to fetch data from my functional Wordpress website to an AngularJS application. Everything is functioning properly, however when I attempt to access post meta such as "_ait-item_item-data", it returns an error stating "u ...

Struggling to disable a checkbox for individuals with disabilities

function checkenabledisable() { if ($("#completebatch").is(':checked')) { $('.commoncheckbox').prop("checked", true); } else { $('.commoncheckbox').prop("checked", false); } $('.disabled-check').remo ...

Implementing functions within a loop with the help of requirejs

I'm experiencing a challenge with calling functions within a loop across different modules using requirejs. The function call within the loop is located in module A and triggers a function in module B that initiates an Ajax request using jQuery. Each ...

Various activities tailored to the amount of clicks

I've encountered some difficulties trying to achieve a specific functionality: https://jsfiddle.net/CreativeAU/ys12ed05/ warningbutton.onclick = function buttonClicks() { count += 1; if (count > 1) { window.location.href = "http://www.google.com. ...