Arranging a collection of items by a specific attribute

const oddArray = [
    { name: "1", desc: "in odd", cat: "1" },
    { name: "3", desc: "in odd", cat: "2" }
];

const evenArray = [
    { name: "1", desc: "in even", cat: "1"},
    { name: "2", desc: "in even", cat: "1" },
    { name: "4", desc: "in even", cat: "1" }
];

I am trying to combine these arrays into a single array where objects are grouped based on the 'cat' property.

Once merged, I would like to sort this consolidated list by the 'name' property. Are there efficient ways to achieve this?

Answer №1

Are you in need of a code snippet similar to this?

var array1 = [
  { name: "1", desc: "in odd", cat: "1" },
  { name: "3", desc: "in odd", cat: "2" }
];

var array2 = [
  { name: "1", desc: "in even", cat: "1" },
  { name: "2", desc: "in even", cat: "1" },
  { name: "4", desc: "in even", cat: "1" },
];
var array3 = array1.concat(array2);

var objConsolidated = {};

array3.forEach(element => {
  if(objConsolidated[element.cat]){
    objConsolidated[element.cat].push(element);
  } else {
    objConsolidated[element.cat] = [];
    objConsolidated[element.cat].push(element);
  }
});

console.log(objConsolidated);

Answer №2

Do You Understand?

var list1 = [
    { name : "1", desc: "in odd", cat:"1" },
    { name : "3", desc: "in odd" ,cat:"2" }
];

var list2 = [
    { name : "1", desc: "in even", cat:"1"},
    { name : "2", desc: "in even", cat:"1" },
    { name : "4", desc: "in even", cat:"1" }
];

function getItemsByCategory(category){
    var mergedList = [list1, list2].flat();
    return mergedList.filter(item => item.cat == category);
}

console.log(getItemsByCategory("1"));

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

Having trouble retrieving the ID of a button?

I'm attempting to retrieve the ID of a button, but I seem to be getting the ID of the surrounding div instead. This is not the desired outcome. Here's my current approach: HTML <div class="container container-about container-login"> ...

What is the best way to create query strings for AJAX URL using jQuery or JavaScript?

At the moment, I am implementing ajax and jquery to dynamically update search results based on different filtering categories within a form. My challenge lies in the fact that I aim to pass varying variables to the URL used for ajax, derived from checkbox ...

How can I store items in a JavaScript array so that they are accessible on a different page?

I'm running into an issue with my PHP website. Each item has a "request a quote" button that, when clicked, is supposed to add the item name to an array using JavaScript. This array should then be added to the "message" field on the contact.php form. ...

What is the best way to execute a function individually for every tag within a vue.js application?

I'm currently exploring the world of Vue JS and I thought it would be interesting to experiment with something new. Sometimes looking at the code first makes understanding it much easier than a lengthy explanation. Check out this code snippet on jsFi ...

The function to focus on this.$refs[("p" + index)] element is not available

I need help transforming a div into an input box when clicked, allowing me to edit the post inside a loop. Here is the button found on the post: <a @click="setFocusEdit(index)" v-if="isAuthor(post)" href="#" >Edit Me</a> And here is the spec ...

Update the page once the Ajax call is completed

On my website, I have a setup with two pages. The first page allows users to select an item using a <select> element. Upon selecting an item, a form is shown automatically via an AJAX call. This form pulls data from a MySQL database and displays it ...

Unable to locate child after adding element to HTML

I have been attempting to add a child element to my HTML document, and although I can see it in the source code, it doesn't display on the screen as expected. It's quite baffling. Here is the HTML code snippet: <!DOCTYPE html> <html> ...

Ways to incorporate a nested table into a datatable

Currently, I am working on adding a nested table to each row of a jQuery datatable using legacy datatables. I attempted to implement the example found on datatables.net for child rows and adjusted it to fit my requirements. My goal is to have the child row ...

Steps for updating text within an object in Angular

details = [ { event: "02/01/2019 - [Juan] - D - [Leo]", point: 72 }, { event: "02/01/2019 - [Carlo] - N - [Trish]", point: 92 } ]; I am attempting to modify the text within the titles that contain - N - or - D - The desired outcom ...

Issue with Laravel: CKEditor text not loading HTML tags

Could you assist me with this? click here for the image description image description available here ...

Navigating through routes using the Express framework in Node.js

In the controller, I have implemented the following route methods: getListaUsuarios() { this.app.get("/api/usuario", (req, res) => { this.usuario.getListaUsuarios().then((results) => { return res.status(200).json(results); ...

The Vue.js scripts and styles declared in the index.html file seem to be malfunctioning

I acquired a theme that includes html, css3, and js files, and I included the file path as shown below: <!-- Basic --> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Porto - Responsive HTML5 Te ...

What is the best way to arrange an item in alphabetical order before including it in the list?

For an assignment, I am required to identify and list each word in a line along with the number of times it appears. Although I have completed this step, I am struggling to compare the newly found word to those already listed and determine the index for ...

The setInterval function continues executing even after the page has been changed

I'm encountering an issue with my function where it continues to run even after the page has changed, resulting in an error. How can I go about stopping this behavior? Thank you! componentDidMount() { var current = 0; var slides = document.g ...

Exploring a MongoDB database through mongoose to retrieve an object's properties

I am facing an issue with a simple task that just won't work. In my MongoDB collection called "fruits", I have the following documents: { "_id" : ObjectId("5f4d0d1f4e31f73410733d8b"), "name" : "Banana", "co ...

How can we achieve the same functionality as React Native's { flex: 1 } in React JS?

I've been diving into React Native development, and now I'm exploring React.js for web applications. However, I'm facing a challenge in creating a simple View that takes up the entire screen to begin experimenting with different components. ...

JavaScript: Efficiently Replacing Multiple Text Instances

To ensure that users do not input multiple empty paragraphs in the text editor, I have found a method to eliminate a single <p><br></p> from the text within the editor message. var str = content.replace('<p><br></p> ...

Running an Angular-made Chrome extension within an iframe: A guide

I'm currently working on creating a Chrome extension that displays its content in a sidebar rather than the default popup. I've come to realize that in order to achieve this, I need to use an iframe due to the limitations of the default chrome ex ...

JavaScript library unsuccessful in transferring data to PHP script

I am facing an issue while trying to transfer variables from javascript to a php file for execution. The problem is that the php file is not being called or executed, even though I have confirmed that it works properly when tested individually. $(function ...

Downsides of exclusively using TypeScript for all components in a React project with .tsx files

While working on TypeScript + React (JSX) code, I encountered a problem where I mistakenly wrote JSX with the file extension of .ts, causing issues. It can be resolved by changing the extension to .tsx, but I wondered if it would be more convenient to have ...