What is the best way to sort an array within an object?

I'm having difficulty filtering an array within an object based on a condition (specifically, filter if value1 <> value2 and toggle is true)

myObject = { 
    value: 1, 
    capacitiesArray: [{value1: 10, value2: 10}, {value1: 10, value2: 20}] 
}

the desired output should be

filteredObject = { 
    value: 1, 
    capacitiesArray: [{value1: 10, value2: 20}] 
}

I've implemented a function called "filterObject", that takes "myObject" and "toggle" as parameters (if toggle is true then filter "capacitiesArray" else do not filter "capacitiesArray")

I attempted to achieve this by the following code, but it seems to not work as expected :(

I suspect there may be an issue with object mutation

function filterObject(myObject: MyObject, toggle: boolean): MyObject {
if(toggle) {
  const rows = myObject.capacitiesArray; 
  const capacitiesArray = rows.filter((row) => row.value1 !== row.value2); 
  myObject.capacitiesArray = capacitiesArray; 
  return myObject; 
  } 
return myObject; 
}

Here's a link to unit test the function https://stackblitz.com/edit/github-test-run-draft-gczdsg?file=src%2Fapp%2Fapp.component.spec.ts

in app.component.spec.ts

the second test "filterRowOnCosCoeValue should filter operationalCapacities when toggle on" passes (which is correct, since the expected result is "expectedOperationalNoticeMock")

however, it should not pass when I provide "operationalNoticeMock" as the expected result (it still passes, giving a false positive result)

Any suggestions or help would be greatly appreciated! :) Thank you!

EDIT: additional details regarding the false positive test passing

Answer №1

This issue arises due to object mutation problems, as you have correctly pointed out. In JavaScript, Objects are passed by reference, so simply comparing objects will not reflect any changes if the object has been mutated. This is why a deep comparison is necessary.

To test this, try the following:

  it('filterRowOnCosCoeValue should filter operationalCapacities when toggle on', () => {
    const expectedResult = JSON.stringify(operationalNoticeMock);
    const result = JSON.stringify(filterObject(operationalNoticeMock, true));
    expect(result).toEqual(expectedResult);
  });

I have created a fork of the code in the stackblitz environment.

EDIT

Currently, the test is failing. However, if you replace the variable with expectedOperationalNoticeMock, the test will pass successfully.

Replace this line:

const expectedResult = JSON.stringify(operationalNoticeMock);

With this one:

const expectedResult = JSON.stringify(expectedOperationalNoticeMock);

The test will then pass as expected.

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

What is the process for inserting a new item into a mongoose array?

I'm currently developing a confidential web application. Below is the layout I've created for the user. const itemsSchema = { name: String } const userSchema = new mongoose.Schema({ username: String, email: String, password: String, M ...

Once deployed, Google Cloud Function experiences delayed execution

I have implemented a Cloud Function that executes the following steps: retrieving data from an API formatting the retrieved data saving the data in Firestore Here is the code snippet for my implementation: exports.syncItems = functions.https.onRequest((r ...

Utilizing AJAX to dynamically update a div's content by extracting a specific div from the retrieved data

Although I believe my code is correct, I am not very familiar with AJAX and have been struggling for hours to get it right. I've tried various approaches, including using filters, but nothing seems to work. The issue I'm facing is that the chat m ...

The filter and search function in the table is malfunctioning

Recently, I developed a page designed for saving actors in an array and displaying them in a table. However, my attempt to add a search feature by name failed. If anyone has encountered a similar issue before and knows how to resolve it, please share your ...

Steps for customizing the dropdown arrow background color in react-native-material-dropdown-v2-fixed

Currently, I am utilizing react-native-material-dropdown-v2-fixed and I am looking to modify the background color of the dropdown arrow. Is there a way for me to change its color? It is currently displaying as dark gray. https://i.stack.imgur.com/JKy97.pn ...

Issues with submitting Report Form on website (php, html)

I'm having trouble with my email not sending from a one question report form on a small website I am creating. I suspect there may be an issue with the php or html code, as I am still learning about forms. Any assistance is greatly appreciated! Here& ...

Add a variable from a callback function in AJAX's success response

Is there a way to effectively utilize the variable in the appended message of the AJAX success call? http://codepen.io/anon/pen/fdBvn data['name'] = $('#goofy').val(); $.ajax({ url: '/api/1/email/test/', data: data, type ...

When using props.onChange(e.target.value) in a textField component in Material UI, it unexpectedly returns an object instead of a value

function FormInput(props) { const classes = formInputStyles(); return ( <div> <TextField onChange={(e) => props.onChange(e.target.value)} InputProps={{ classes, disableUnderline: true }} {...pro ...

Is it possible to resize without defining dimensions?

Currently, I am working with Access 2010 on Win7. I have recently discovered that I can dynamically size my arrays at runtime simply by using ReDim arrayName(x) without having to declare the array with Dim arrayName() first. Sub FooBar() ReDim myArray( ...

Error VM1673:1 SyntaxError was raised due to an unexpected token '<' appearing in the code

I am facing an issue with the following JS code for AJAX form submission using PHP 8. When I check the chrome browser console, I encounter the error message: "Uncaught SyntaxError: Unexpected token '<', " <fo"... is not valid JSON." What ...

UserEvent from React Testing Library does not properly wait for render updates

I encountered a failure in a simple RTL test. The issue relates to the TodoList component provided below: import React, { useState } from "react"; import { FaTrash } from "react-icons/fa"; // Code for TodoItem component and TodoList c ...

Leveraging the ReactJS Hook useState for detecting Key press events

As I am in the process of constructing a piano, I want it to showcase certain CSS styles when the user "presses" specific keyboard buttons (via keydown event) - even enabling the simultaneous clicking of multiple different buttons. Once the user releases t ...

Update the status of the reactive form control to invalid

I'm attempting to mark a form control as invalid, however, the following code snippet is not producing the desired result this.currencyForm.controls['currencyMaxSell'].setErrors({smallerThan: true}) ...

Using React and TypeScript, open the initial tab from a mapped array with an accordion component

{accordion.map(accordionItem => ( <AccordionItem key={accordionItem.title} text={accordionItem.text} title={accordionItem.title} ></AccordionItem> ...

determining the quantity within a collection of items

Is there a way to determine the order of an element within a set when clicked? For example, if I click on the third element in a set, can I get it to display as three? Check out this jsfiddle example for reference: http://jsfiddle.net/vtt3d/ ...

Angular drag and drop feature for interacting with intersecting elements like rows and columns within a table

I am currently working on implementing two intersecting drag and drop functionalities using cdkDragDrop. Although I generally try to avoid using tables, I have created one in this case for the sake of easier explanation. Here is the link to StackBlitz: ht ...

Creating an array of objects in Node.js can be achieved by simply declaring an array

Here's the structure of my class: var Coin = { _id: null, createGame: function(id) { this._id = id; }, start: function() { } }; My issue is that I am unable to create an array of objects, as I can only create one. Can someo ...

What could be causing my Amazon slot to return an undefined value?

Currently, I am working through this tutorial: https://medium.com/@itsHabib/integrate-an-amazon-lex-chatbot-into-a-react-native-app-1536883ccbed Upon running my chatbot, the JSON output is as shown below: { "dialogState": "Fulfilled", "intentName": ...

extracting data from json using javascript

Here is the data in JSON format var testData = {text: '{"status":200}'}; I am attempting to extract the status using this code: console.log(testData.text.status); However, it returns undefined Could you please provide guidance on how to succ ...

Creating Awesome Icons in Kendo Grid with Code In this tutorial, we will learn how to programm

Looking to have a Kendo grid display a green fas-fa-clock icon if isActive is true, and a grey far-fa-clock icon if false. Clicking on the icon should toggle between true and false. Currently, the grid just shows the word true or false in the column. Cod ...