Sort through an array of objects by a specific field in each object

Imagine having an array containing different objects:

[
  { "category": 121, "item": "item1" },
  { "category": 128, "item": "item2" },
  { "category": 130, "item": "item2" },
  { "category": 130, "item": "item2" }
]

Your goal is to filter this array and generate new objects based on the item field.

The desired outcome should look like this:

[
  { "category": 121, "item": "item1" }
]

[
  { "category": 128, "item": "item2" },
  { "category": 130, "item": "item2" },
  { "category": 130, "item": "item2" }
]

In order to achieve this task efficiently, I recommend using typescript and lodash. Although attempts with lodash groupBy and ES6 mapping were made previously, they did not yield successful results. Perhaps a cleaner solution involving smart usage of loop functions could provide an easier way to accomplish this objective.

Answer №1

To filter the array based on a specific condition, you can utilize the .filter method. See below for an example:

let filteredArray1 = array.filter(item => item.type === 'type1');
let filteredArray2 = array.filter(item => item.type === 'type2');
...

Answer №2

To filter out an array to a new array object, you can use the Array.filter function. In this example, I have defined a variable called searchModels which contains a list of models that you want to filter. Within the filter function, the condition searchModels.indexOf(item.model) is used to check the model value.

var array = [
  { "type": 121, "model": "model1" },
  { "type": 128, "model": "model2" },
  { "type": 130, "model": "model2" },
  { "type": 130, "model": "model2" }
];


var searchModels = ['model1', 'model3'];
var filteredArray = array.filter((item) => { return searchModels.indexOf(item.model) !== -1 });
console.log("Original: ", array);
console.log("Filtered: ", filteredArray);

Answer №3

One way to achieve this is by creating a Map for easier searching purposes. Let's say we start with some original data and map it accordingly:

var newData = new Map([]);

var originalData = [{"category": 10, "name": "item1"}, {"category": 10, "name": "item2"}];
var formattedData = originalData.map(obj => { 
  newData[obj.name].push(obj.category); 
});

This will result in a structure like this:

newData = ([
    [ "item1", "10" ],
    [ "item1", "10" ],
    [ "item2", "7" ]
]);

Now, you can easily retrieve values based on the model key such as newData["item2"] = ["7"]

Answer №4

To group all items together, one can utilize the Array.prototype.reduce method.

let array = [
  { "type": 121, "model": "model1" },
  { "type": 128, "model": "model2" },
  { "type": 130, "model": "model2" },
  { "type": 130, "model": "model2" }
]

let all = [...array.reduce((acc, curr) => {
  acc.has(curr.model) ? acc.set(curr.model, [...acc.get(curr.model), curr]): acc.set(curr.model, [curr]);
  return acc;
}, new Map()).values()];
console.log(...all)

Answer №5

Hey @raulicious, check out this code snippet:

var arrayList= [
  { "type": 121, "model": "model1" },
  { "type": 128, "model": "model2" },
  { "type": 130, "model": "model2" },
  { "type": 131, "model": "model2" }
];
   var filteredArray = [];
   var filtered = [];
   
   arrayList.sort((a, b) => {
         if(a.model == b.model) {
             filtered.push(b);
         } else {
             filtered.push(b);
             filteredArray.push(filtered);
             filtered = [];
           }
       filtered.push(a);
       filteredArray.push(filtered);
     });
    console.log(filteredArray);

I'm aware that there is some redundant code here, but I plan to refactor it soon.

Answer №6

Check out how lodash can assist you

var data = [
  { "type": 121, "model": "model1" },
  { "type": 128, "model": "model2" },
  { "type": 130, "model": "model2" },
  { "type": 130, "model": "model2" }
];

var grouped = _.groupBy(data, function(item) {
  return item.model;
});

console.log(grouped);
<script src='https://cdn.jsdelivr.net/lodash/4.17.2/lodash.min.js'></script>

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

"Encountered a problem while attempting to download the .xlsx file through http.get in an angular application interfacing

Attempting to download a .xlsx file using Angular 7 and web API in C#, encountering the following error: https://i.sstatic.net/7pwDl.png The code snippet from my service.ts is provided below: public exportExcelFile(matchedRows: string, reportInfoId: num ...

NestJS Ensures Type Safety for Mongoose Models, but Model Functions Expecting Incorrect Types (Any)

Shema Interfaces export interface MyCat { name: string; color: string; } export type Cat = MyCat & Document; export const CatSchema = new Schema({ name: { type: String, required: true, }, color: { type: String, required: tr ...

Merge type guard declarations

After studying the method outlined in this post, I successfully created an Or function that accepts a series of type guards and outputs a type guard for the union type. For example: x is A + x is B => x is A | B. However, I encountered difficulties usin ...

Opting in to an Observable depending on specific criteria

Introduction I am utilizing Reactive Forms that span across two tabs on a lengthy page with a Submit button at the bottom. Validation occurs when the Submit button is clicked. If validation fails, the page should scroll to the error field. I am successf ...

The properties required for type 'Subscription' are not present

I encountered an issue in my IDE while trying to run the following code. Within my component, I am making a call to a service in the ngOnInit method to fetch some data. This service, in turn, calls another service to gather additional information before f ...

Incorporating a class element within an Angular 2 directive

When working with Angular 2 directives, one way to add an element is by using the following code: this._renderer.createElement(this._el.nativeElement.parentNode, 'div'); After adding the element, how can I set its class and keep a reference to ...

Showing information from Flask API utilizing Angular with underscores

I'm in the process of creating components from my Flask API. Upon accessing the route, I can view the data for the desired objects. However, upon attempting to display it on the front end through interpolation, I am only able to see certain properties ...

Is it possible to use ngFor with an object instead of an array?

Encountering this console error: Unable to locate a supporting object '[object Object]' of type 'object'. NgFor specifically requires binding to Iterables like Arrays. services.ts private url = "https://api.iextrading.com ...

Error in TypeScript not being caught in React due to incorrect type detection

Could you assist me in grasping the workings of TypeScript? I am currently trying to learn it but am struggling with understanding certain behaviors. Example 1: The issue lies in the type errors not being detected, please refer to the commented message wi ...

Utilize mapping to object and preserve type inference

I am currently developing a function that utilizes a map function to map objects. interface Dictionary<T> { [key: string]: T; } function objectMap<TValue, TResult>( obj: Dictionary<TValue>, valSelector: (val: TValue) => TResult ...

When using ngStyle to bind a variable, the binding variable will be null

Currently, I am attempting to utilize ngStyle to set the background image. <div class="artist-banner fluid-banner-wrapper" [ngStyle]="{'background-image': 'url(../imgs/banner/' + event?.category + '.jpg)' }"> The fun ...

The post method is functioning properly in browsers such as Firefox, Internet Explorer, and Chrome; however, it is not working in the Edge browser

I am encountering an issue with a post method in the Edge browser. Even though I am able to receive responses for the same request in other browsers like Internet Explorer, Chrome, and Firefox, Edge seems to be not responding at all. Despite conducting a s ...

Angulating Service Testing

I am encountering an issue that I'm not sure how to resolve because I am inexperienced when it comes to testing. Currently, I am testing a service that includes the following code: import { Injectable } from '@angular/core'; import { Endpo ...

Typescript: defining an interface that inherits properties from a JSON type

When working with TypeScript, I've utilized a generic JSON type as suggested in this source: type JSONValue = | string | number | boolean | null | JSONValue[] | {[key: string]: JSONValue} My goal is to cast interface types matching JSON to and ...

Troubleshooting Authorization Header Issue in Angular 5

I created an Interceptor to include an Authorization token in all HTTP Requests, but unfortunately it's not functioning as expected. I've double-checked my code and everything seems correct, so I'm wondering if there's something crucial ...

Steps for configuring Types in Graphql Codegen

I have successfully implemented a Vue 3 component that utilizes Urql to query a Hasura graphql endpoint. The query is functioning properly, but I am now focused on enhancing the type safety of the component. My approach involves using graphql Codegen to g ...

Angular2 route-driven themes

Exploring Different Themes for Two Routes: /books and /paintings Seeking a Solution to Include Specific Stylesheet Links in index.html For the /books route, I wish to include: <link rel="stylesheet" href="/assets/css/reading-theme.css" /> And for ...

Steps for adjusting the status of an interface key to required or optional in a dynamic manner

Imagine a scenario where there is a predefined type: interface Test { foo: number; bar?: { name: string; }; } const obj: Test; // The property 'bar' in the object 'obj' is currently optional Now consider a situatio ...

Refresh the table following deletion of a row from firebase

I have developed an application where I display data from a firebase object in a table. However, I have encountered an issue where I need to manually refresh the page every time I remove a row from the table. Is there a way to automate this process? The sa ...

Integrating jquery into an angular project

I am facing an issue setting up jquery in an angular 6 project. When I try to import it in the ts file, I encounter the following error: Error: This module can only be referenced with ECMAScript imports/exports by turning on the 'allowSyntheticDe ...