Combine and convert an array of objects

Implementing JavaScript functional programming techniques, how can the `status` field of `arr1` be aggregated/counted and then transformed into an array of key/value objects in `arr2`?

arr1 = [
  {'task':'do something 1', 'status':'done'} , 
  {'task':'do something 2', 'status':'done'} , 
  {'task':'do something 3', 'status':'pending'} , 
  {'task':'do something 4', 'status':'done'}
];

// Aggregate arr1 `status` field and transform to:

arr2 = [
  {key:'done', value: 3},
  {key:'pending', value: 1}
];

Outlined below is my work-in-progress solution that currently addresses only the aggregation part. The transformation part still needs to be implemented.

var arr2 = arr1.map(function(item) {
    return item.status;
  }).reduce(function(acc,curr,idx){
    if(acc[curr] === undefined) acc[curr] = 1;
    else acc[curr] += 1;
    return acc;
  }, []); 

Answer №1

After thoroughly researching and experimenting, I have developed an optimized solution that combines aggregation with the desired transformation:

var newArr = Object.keys(newArr = oldArr.map(function(element) {
    return element.status;
}).reduce(function(accumulator, current){
    accumulator[current] = accumulator[current] + 1 || 1;
    return accumulator;
}, [])).map(function(item){
    return {key: item, value: newArr[item]}
});

Answer №2

If you want to avoid looping over an array multiple times to find the count of a specific status, consider using Array.prototype.forEach(). Alternatively, you can switch from using an array to using an object.

newArr = [
  {'task':'finish task A', 'status':'complete'} , 
  {'task':'finish task B', 'status':'complete'} , 
  {'task':'start task C', 'status':'in progress'} , 
  {'task':'finish task D', 'status':'complete'}
];

var counter = {};
newArr.forEach(function(elem){
  if(!counter[elem.status])
    counter[elem.status] = 0;
  
  counter[elem.status]++;
});
console.log(counter);

Answer №3

When storing the output value as an array, it is important to verify if the key 'status' is present or not. If it is present, increment its value.

arr2 = [];
arr1.forEach(function(item){
  var keyPresent = false;
  for(var i = 0, len = arr2.length; i < len; i++) {
      if( arr2[ i ].key === item.status ){
         keyPresent = true;
         arr2[ i ].value++
      }
  }
  if(!keyPresent){
    arr2.push({key: item.status , value : 1})
}

The expected output is

arr2 = [
  {key:'done', value: 3},
  {key:'pending', value: 1}
];

Answer №4

let completedTasks = tasks.filter(task => task.status == 'completed');
let pendingTasks = tasks.filter(task => task.status === 'pending');
taskCounts = [
   {category: 'completed', count: completedTasks.length}, 
   {category: 'pending', count: pendingTasks.length}
];
console.log(taskCounts);

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

Cluster associative array elements based on their values while keeping the original keys intact within each cluster

I am looking for a way to group Associative Arrays with their `keys. Currently, I am unsure of the correct syntax to achieve this. Here is the code I have at the moment: $associativeArray = array("Ripe Mango"=>"Yellow", "Strawberry"=>"Red", "Lemon" ...

Guide on displaying API data within nested fields in ReactJS

import axios from 'axios' import { CART_ADD_ITEM } from '../constants/cartConstants' export const addToCart = (uid, qty) => async (dispatch, getState) => { const { data } = await axios.get(`/api/v1/`) dispatch({ ...

Refresh the PHP variable using JavaScript's .innerHTML function

Similar Question: How do I set the value of a select box element using javascript? I am attempting to dynamically update a table based on query results when a selection option changes. The sample code provided below functions correctly. However, when ...

The Jqueryui image link is not displaying the image despite no error being reported

Can anyone help me figure out what I'm missing? I'm currently working with ASP.NET MVC 5 and have downloaded the JqueryUI combined via Nuget package. Despite no error references for css/js files, the close button is still not showing in the ima ...

Exploring the intricacies of React's useEffect: Solving the challenge of updating data when two separate dependency arrays are

I am facing an issue with two different useEffect hooks where the dependency arrays are different. const [dateFilterSort, setDateFilterSort] = useState({ queryText: initialQueryText(params.sortName), cardText: initialCardText(params.sortName), ...

Struggling with JQuery to revert an element back to its original position after the mouseout event

Hello all, I'm a newcomer here and I've been trying my hand at some basic JQuery. However, I've encountered an issue that I could use some help with. Have you ever come across those boxes on websites where when you hover over them, an arrow ...

"NodeJS Express: The intricacies of managing overlapping routers

While constructing a NodeJS express API, I have encountered a peculiar bug. It seems that some of the endpoints are overlapping, causing them to become unreachable as the request never completes and ends up timing out. For example: const load_dirs = (dirs ...

apply a course to the designated element

Alright, I have this piece of code that deals with session and page requests. // Let's start our session session_start(); // Now let's check if there is a page request if (isset($_GET['page'])) { // If there is a requested page, we ...

Using a combination of stringify, regular expressions, and parsing to manipulate objects

As I review code for a significant pull request from a new developer, I notice their unconventional approach to editing javascript objects. They utilize JSON.stringify(), followed by string.replace() on the resulting string to make updates to both keys a ...

Executing jQuery callback functions before the completion of animations

My issue revolves around attempting to clear a div after sliding it up, only to have it empty before completing the slide. The content I want to remove is retrieved through an Ajax call. Below you will find my complete code snippet: $('.more& ...

The functionality of the TURF booleanwithin feature is malfunctioning and not producing the

Currently, I am working on validating whether a polygon is completely within another polygon. However, there are cases where more complex polygons should return false, but turf interprets them as valid. If you'd like to see the sandbox, click here: ...

Displaying a div when an ng-repeat directive is devoid of content, incorporating filters in AngularJS

Currently, I am in need of a solution to display a specific div when my ng-repeat list is empty. The scenario involves a list containing various types of ice cream (with search filter functionality). What I aim to achieve is showing a designated div when t ...

Creating a task management system using HTML, CSS, and JavaScript that utilizes local

I have been extensively researching how to create a to-do list using JavaScript with local storage, but unfortunately, I have not been able to find exactly what I am looking for. Is there a way for me to set up a to-do list and input data before actually ...

Menu/navigation bar designed with floating lines and an array of color options

I'm currently working on implementing this specific menu into my Wordpress site. My main concern is figuring out how to customize the hover effect for each navigation item. Currently, the float line changes to red (background-color:#800; height:2px;) ...

Proper JSON unmarshalling format required

I'm struggling to create a data structure in Golang for this JSON object: { "response": [1702487, { "uid": 150261846, "first_name": "Олег", "last_name": "Брейн" }, { "uid": 53260546 ...

Pop up a modal within a jQuery function to save modifications and return to the original function

As a newcomer to jQuery and Bootstrap, I have encountered a situation where a jQuery function is triggered from a click event, opening a modal with input fields. After saving the data entered in the modal, I need to return to the original jQuery function t ...

Determining the y coordinates based on x and z values for a 3D plane

I've created a 3D circular plane that has been rotated by 45 degrees along the x-axis: https://i.sstatic.net/Ri1Ps.png I need help determining the y-coordinate of the plane based on the x and z coordinates. How can I interpolate the plane to calcula ...

Utilize the Image URL for training your Tensorflow.js application

I'm currently exploring how to use images sourced from the internet for training my neural network. I am utilizing an Image() object to generate the images and pass them to tensorflow. Despite my understanding that Image() should return a HTMLImageEle ...

What other methods can be used to initiate an Ajax request?

I'm curious about the most efficient approach to making an AJAX call. My current code works perfectly fine: $.ajax({ url: "/rest/computer", type: "GET", dataType: "json", data: { assessmentId: "123", classroomId: " ...

Easy way to make a jQuery getJSON request to Twitter

After browsing through numerous Twitter and jQuery related questions, I have yet to find a solution to my specific issue. My goal is simple - to retrieve 5 "tweets" from a public user. At this stage, I am not manipulating the data in any way, but for some ...