Implementing conditional logic when adding values to an array of objects in JavaScript

Below is my array of objects:

 var filterStatus = [{ doc_count: 49, key: "Completed", color: "#1DC9B7" }, { doc_count: 147, key: "Failed", color: "#F14C69" }, { doc_count: 321, key: "In Progress", color: "#FFC568" }, { doc_count: 29, key: "Started" }];

I am looking to extract results that include the statuses Completed, Failed, and In Progress (Should also include Started status).

This is the code I am currently using:

var result = filterStatus.filter(obj => { if(obj.key == 'Started' || obj.key == 'In Progress'){ return obj}} ).map(obj => obj.doc_count).reduce((p, c) => p + c, 0);

The current result obtained is 350.

The expected output should be as follows:

[{ doc_count: 49, key: "Completed", color: "#1DC9B7" }, { doc_count: 147, key: "Failed", color: "#F14C69" }, { doc_count: 350, key: "In Progress", color: "#FFC568" }];

Note: The expected output includes an addition based on combining the counts for Started and In Progress under In Progress doc_count.

Answer №1

const filterStatusData = [{ doc_count: 49, key: "Completed", color: "#1DC9B7" }, { doc_count: 147, key: "Failed", color: "#F14C69" }, { doc_count: 321, key: "In Progress", color: "#FFC568" }, { doc_count: 29, key: "Started" }];
// Filtering out "Started" status
const updatedResult = filterStatusData.filter(({key}) => key !== "Started");
// Updating the "In Progress" status count
updatedResult.find(({key}) => key === "In Progress").doc_count += filterStatusData.find(({key}) => key === "Started").doc_count;
console.log(updatedResult)

Answer №2

Utilize the reduce and map functions individually

var filterData = [{
  doc_count: 49,
  key: "Completed",
  color: "#1DC9B7"
}, {
  doc_count: 147,
  key: "Failed",
  color: "#F14C69"
}, {
  doc_count: 321,
  key: "In Progress",
  color: "#FFC568"
}, {
  doc_count: 29,
  key: "Started"
}];
 var val=filterData.map(function(e){
  if(e.key=="In Progress" || e.key=="Started")
    return e.doc_count
  else
    return 0}).reduce(function(acc,e){return acc+=e},0)
var result = filterStatus.filter(function(obj) {
if(obj.key == 'In Progress')
obj.doc_count=val;
      if (obj.key == 'Completed' || obj.key == 'In Progress' || obj.key == 'Failed')
        return obj;
    })
   console.log(result)
 

Answer №3

var filterData = [{ doc_count: 49, key: "Completed", color: "#1DC9B7" }, { doc_count: 147, key: "Failed", color: "#F14C69" }, { doc_count: 321, key: "In Progress", color: "#FFC568" }, { doc_count: 29, key: "Started" }];


function combineInProgressStarted () {
 return filterData.filter(({key}) => {
   return ['In Progress', 'Started'].indexOf(key) > -1;
}).reduce((acc, status) => {
  acc.doc_count += status.doc_count;
  if (status.color) {
    acc.color = status.color;
  } 
  return acc;
  }, { key: "In Progress", doc_count: 0 })
}



filterData.filter(({ key  }) => ['Completed', 'Failed'].indexOf(key) > -1).concat([combineInProgressStarted()])

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

List that scrolls with a stationary button

I am working on an interface that includes a button with a dropdown list. Here is an example: <a href="https://jsfiddle.net/DTcHh/16589/" rel="nofollow">jsfiddle</a> While the list is scrollable, I am looking to add a fixed button at the botto ...

What is the best way to align a modal with a layout when it appears far down the components hierarchy?

Struggling with creating a React modal and facing some issues. Let's consider the structure below: React structure <ComponentUsingModal> <Left> <ButtonToActivateModal> ... </ButtonToActivateModa ...

Vue.js: Trouble with updating the v-for list

Here is a list I have: <ul id="tab"> <li v-for="list in names"> {{ list.personName }} </li> </ul> And then, I have this Vue object set up: var vm = new Vue ({ el: '#tab', data: { ...

Using the event object in the onClick handler within React applications

In my React app, I have implemented a feature where clicking on a column heading sorts the data in the table using merge sort algorithm My goal is to pass both the data (an array of objects) and the event object to the sorting function. However, I am faci ...

Activating object functions through a click

Currently, I am in the midst of creating an interactive story using Jquery. One challenge I am facing is how to dynamically change the text every time a button is clicked to display the next dialogue function. To tackle this issue, I have structured an o ...

it results in an error when attempting to deconstruct an object

Using a style object in a component <Temp styles={{fontWeight: 'bold', fontSize: '1.6'}} ...otherprops /> Encountering an error while deconstructing the style object Cannot read property 'fontSize' of undefined. The d ...

What is the reason behind JSLint's preference for x === "undefined" over typeof x == "undefined"?

I'm feeling lost when it comes to JSLint. Initially, my code checked if div:jqmData("me") was undefined in this way: if ( typeof el.jqmData("me") == "undefined" ? el.not(':jqmData(panel="main")').length > 0 : el.not(':jqm ...

What is the technique used by express.js to handle ReferenceError?

// Here is a sample code snippet app.get("/test", (req, res) => { return res.status(200).send(SOME_UNDEFINED_VAR); }); If a ReferenceError occurs, express.js will automatically send a 500 error response. express.js logs the ReferenceError to std ...

Modify the Google Translate dropdown using programming techniques

Recently, I attempted to integrate the Google Translate dropdown feature into a website using the following code snippet: function googleTranslateElementInit() { new google.translate.TranslateElement({ pageLanguage: 'en' }, 'google ...

Angular JS does not acknowledge null values

Within my controller, the variable $scope.test is assigned a value from the server. When this value is null, line 1 of the code below prints 'null', however it still enters the else condition. I have attempted to use $scope.test != null and $scop ...

What could be the issue causing Vue to not start up properly?

I have been working on a Rails application and have integrated some Vue components into the pages. The components range from simple dynamic lists to more complex implementations with nested components. Let me walk you through how it all functions with som ...

Tips on setting up the table with php and javascript

My PHP and JavaScript code displays data in the wrong format. The row consists of classcode, courseNumber, courseDescription, units, time, days, room, but it's not arranged correctly. I want it to display each piece of data under its respective column ...

Find the smallest positive integer not already present in an array of integers, with a focus on efficiency

During an online assessment, I encountered a task to find the lowest positive value of an integer that is not in the given array. Here is the code I used: class Solution { public static int solution(int[] A) { int hold = 1; while ...

In TypeScript, use a Record<string, any> to convert to {name: string}

I have developed a custom react hook to handle API calls: const useFetch: (string) => Record<string, any> | null = (path: string) => { const [data, setData] = useState<Record<string, any> | null>(null); var requestOptions: Requ ...

Executing Java functionalities within JavaScript

Differences in results between Java and Javascript can be observed when working with large integers. For example: getCode(1747,1763,-268087281,348400) in Java returns 1921968083, while in Javascript it returns 2.510115715670451e+22. Is there a way to ach ...

How can I defer Tween.js animation in three.js until a button is specifically clicked?

I am trying to implement a tween animation for my camera in three.js that should only start when a specific object is clicked. This object can be within the scene or it could be a simple HTML button. The code snippet below demonstrates how the camera anima ...

How can you use JavaScript to retrieve the position of an element on a webpage?

As mentioned in the title, I am looking for a way to retrieve the x and y positions of an element relative to its location on the webpage and based on its positioning schemes such as absolute or relative. ...

Exploring various parameters in React JS

Recently, I've been delving into a project using React js, which I initially thought would be similar to React native. Having prior experience with React native, most of React js is familiar to me. However, there are still new concepts I am learning, ...

Does the time complexity change to O(n) when assigning the return value of myArray.reversed() to a pre-existing array? Does this involve copy-on-write functionality?

The Time Complexity of the .reversed() method in Apple docs is stated as O(1). In the code snippet below, arr (line 2) is of type ReversedCollection<Array<Int>>. Why does printing arr (line 3) not display the numbers in reversed order? // 1 ...

Is there a way to place an array within a single row?

I'm looking for a solution to insert an array from a form into one row, rather than each value in its own row. Can someone help me with this? <?php require_once('config.php'); require_once('open_db.php'); $palette=$_POST[&apo ...