Using `reduce` in TypeScript, you can organize an array of objects based on a shared property

Here is an example of an array:

[
  {
    id: '1',
    task: 'Grocery shopping',
    isImportant: true
  },
  {
    id: '2',
    task: 'Meeting',
    isImportant: false
  },
  {
    id: '3',
    task: 'Presentation preparation',
    isImportant: true
  },
]

I want to reorganize this array based on the value of isImportant into the following structure:

{
  importantTasks: [
    {
      id: '1',
      task: 'Grocery shopping',
      isImportant: true
    },
    {
      id: '3',
      task: 'Presentation preparation',
      isImportant: true
    }
  ],
  notImportantTasks: [
    {
      id: '2',
      task: 'Meeting',
      isImportant: false
    }
  ]
}

While I am aware that I can use filter and map for this transformation, I am interested in leveraging reduce in TypeScript for this particular scenario.

Answer №1

To achieve this task, you can utilize the reduce method along with specific conditions:

const tasks = [
  {
    id: '1',
    name: 'Grocery shopping',
    isImportant: false
  },
  {
    id: '2',
    name: 'Meeting with client',
    isImportant: true
  },
  {
    id: '3',
    name: 'Dentist appointment',
    isImportant: true
  },
  {
    id: '4',
    name: 'Exercise',
    isImportant: false
  },
]

const result = tasks.reduce((accumulator, current) => {
if(current.isImportant)
accumulator.importantTasks.push(current);
else
accumulator.normalTasks.push(current);
return accumulator;

},{ importantTasks : [] , normalTasks : []});

console.log(result);

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

Apache conf file configured with CSP not functioning properly when serving PHP files

While configuring the Apache CSP lockdown for a site, I encountered an unusual behavior when opening the same file as a PHP script compared to opening it as an HTML file. The HTML file looks like this: <html> <head> <meta http-equiv= ...

Changing the width of the file input using css

Clicking just below the word demonstration also triggers a click on the input type file. How can this be avoided so that the click event only fires in the intended area regardless of size? <!DOCTYPE html> <html> <body> <style> in ...

Unexpected behavior with onKeyPress in React-Native Windows resulting in missing key press events

Currently, I am working on a Windows app using react-native version 0.54.0. For one of the functionalities, I have incorporated a TextInput element and would like to use onKeyPress. Here is my code snippet: <TextInput ref = { this.setTextInputRef } on ...

Retrieve active route information from another component

We are utilizing a component (ka-cockpit-panel) that is not linked to any route and manually inserted into another component like so: .. ... <section class="ka-cockpit-panel cockpit-1 pull-left"> <ka-cockpit-panel></ka- ...

JSON syntax error: "r" is not a valid token at the beginning position

Currently, I am in the process of developing a web server that is based on STM32 MCU. The workflow involves the browser sending a request to the MCU, which responds with a web HTML file. Users can then adjust parameters and use a form to submit them back t ...

``Is there a way to access the $attrs data of child DOM elements from within a controller?

Imagine having a controller and multiple children DOMs each with their unique data attributes. <!DOCTYPE html> <html ng-app="plunker"> <head> <meta charset="utf-8" /> <title>AngularJS Plunker</title> < ...

What is the best way to showcase the outcome on the current page?

This is a sample HTML code for a registration form: <html> <head></head> <body> <form id="myform" action="formdata.php" method="post"> username:<input type="text" name="username" id="name"><br> password:&l ...

javascript: restrict the quantity of products

As a beginner in javascript, I am currently working on creating a simple RSS reader. However, I am facing a challenge in limiting the number of feeds to 5 items, especially since the target site may have 100 or more feeds. Here's the code snippet I&ap ...

Having difficulty installing npm on Mac m1 with Monterey operating system

npm install npm ERR! code ENOENT npm ERR! syscall open npm ERR! path /Users/ahmed/package.json npm ERR! errno -2 npm ERR! enoent ENOENT: no such file or directory, open '/Users/ahmed/package.json' npm ERR! enoent This issue is likely due to npm n ...

Mismatch between generic types

When working with this code, I encounter a syntax error at m1 and m2. The error message states: Type 'T' is not assignable to Type 'boolean' or Type 'T' is not assignable to Type 'string' interface customMethod { ...

NextJS getStaticProps failing to pass fetched data to the page component

Struggling with passing props from getStaticProps function into template pages in NextJS. Below is the code for the dynamic page template that I am using. // src/pages/blog/[slug].js import React from 'react'; import matter from 'gray-matte ...

Unexpected behavior from Bootstrap within React

I recently started working on a React project that I initiated with the create-react-app command. To incorporate Bootstrap into my project, I added the necessary CDNs to the public/index.html file after generating the project. <link rel="stylesheet" hr ...

Issue with the height of sections in the active menu

While the set-up below is functional for content within section height limits, it fails when exceeding the limit causing overflow. Adding "display: table" or "overflow: hidden" to fix the overflow issue affects the menu's active state behavior. Sett ...

establishing status within enclosed reaction

In the process of developing a react application, I am encountering difficulties in correctly setting the state with the nested response data received from an api. The state is not aligning as desired. Here is the sample response obtained from the api: [ ...

JavaScript: Filtering list by elements that contain a certain value

I have the following collection of objects: [ { employeeId:1 employeeName:"ABC" }, { employeeId:2 employeeName:"ABD" }, { employeeId:3 employeeName:"FEW" }, { employeeId:4 employeeName:"JKABL" },] I am looki ...

Monitoring a specific property within an array of objects with AngularJS

I am facing an issue with the data in my controller $scope.data = { home: { baseValue: "1", name: "home" }, contact: { baseValue: "2", name: "contract" } // numerous ...

Is there a way to extract the "validade" value from the array and retrieve it exclusively?

The following array contains data: {"status":true,"data":[{"id":1,"pessoa_id":75505,"created_at":"2022-02- 01T17:42:46.000000Z","holder":"LEONARDO LIMA","validade&quo ...

To switch to desktop mode, double click; for mobile view, just tap once

I am looking to implement 2 different gestures for a specific feature in my application. Ideally, I want users to be able to double click on a card to open it in desktop view, but if they are using a phone, a single tap should suffice. How can I achieve th ...

Altering the dimensions of radio buttons

I am a newcomer to using material-ui. I am currently working on incorporating radio buttons in a component and would like to reduce its size. While inspecting it in Chrome, I was able to adjust the width of the svg icon (1em). However, I am unsure how to a ...

What is the best way to create a dynamic hyperlink that leads to a detailed information page based on the specific link clicked?

I'm currently working on a web page that displays a list of users, and I want each user's name to be clickable, leading to a page with specific details about that user. I'm new to this field, so I'm unsure where to start. My idea is to ...