Arranging an array in reverse order (starting with underscore) can alter the attributes of the objects within

REVISION:

To provide more clarity on the issue, I have recorded a bug using quicktime. Here is the link for your reference:

For additional code details, please visit:


ORIGINAL INQUIRY:

A strange issue has come up while working with Meteor and its dependency Underscore.js. While sorting an array of objects functions properly, reversing the process seems to cause data loss within the objects.

I have created a table with a sticky header and dynamically populate the table body.

https://i.sstatic.net/XFls4.png

When clicking on a column in the table header, the following code snippet is triggered:

if (sortId != event.target.id) {
    sortAsc = true;
    sortId = event.target.id;
}

if (!sortAsc) {
    requirements = _.sortBy(requirements, event.target.id).reverse();
} else {
    requirements = _.sortBy(requirements, event.target.id);
}

sortAsc = !sortAsc;

CreateTable();

The sortId represents the key being used for sorting, obtained from event.target.id. The boolean sortAsc determines the sorting order. The array requirements holds data structured like:

[
    {
        Status: "Something",
        ID: 1,
        Description: "Hahaha, yes!",
        Category: "Category: Dairy",
        segment: 1
    },
    {
        //etc...
    }
]

Through Underscore.js, the array is sorted with

_.sortBy([collection], [property to sort by]);
. However, upon reversing the sorted array, a property deletion occurs in all objects resulting in missing columns and disrupted styling:

https://i.sstatic.net/UaGU0.png

https://i.sstatic.net/WrPbx.png

After reversing the array, the Status property vanishes from all objects causing issues. Even attempts to manually specify a sorting function or reverse standard JavaScript sorting methods also lead to data loss.

If anyone can shed some light on this issue, any assistance would be greatly appreciated!

Answer №1

When using the _.sortBy method in JavaScript, the returned result is an Array object. If you then call reverse() on this array and encounter issues, it's not due to any problem with underscore.</p>

<p>To troubleshoot, try running <code>console.log(Array.prototype.reverse);

The expected output should be something like ƒ reverse() { [native code] }, depending on your browser. Seeing anything other than [native code] indicates a potentially faulty implementation of the reverse() function.

Additionally:

I recommend avoiding the use of reverse() altogether and focusing solely on sorting operations.

requirements.sort((a, b) => {
  const v1 = (sortAsc ? a : b)[sortId];
  const v2 = (sortAsc ? b : a)[sortId];
  return v1 < v2 ? -1 : (v1 > v2 ? 1 : 0);
});

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

Deleting duplicate data based on key values in PHP

Can someone assist me with removing duplicate data based on a key value using PHP? Below is the code I have: $orginalArr = array( array("id"=>1,"name"=>"Raj"), array("id"=>1,"name"=>"Raj"), array("id"=>2,"name"=>"Ram"), array("id ...

"An alternative approach in node.js for implementing an AJAX saving mechanism, similar to the

For my JavaScript (client) + PHP (server) website, I have a system in place to save an "online notepad" from a #textbox textarea to the server: // client-side $("#save-button").on('click', save); function save(e) { $.ajax({ type: "POST", ...

What is the reason for the hotel's Object _id not being saved in MongoDB?

Can you assist with troubleshooting this issue? This is the HotelRoom Module: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const HotelRoomSchema = new Schema({ name : { type : String, require : true ...

When the submit button on the signup form is pressed, two distinct actions are activated to achieve specific outcomes

I am seeking assistance in implementing code that will trigger the following action: Upon clicking the 'Submit' button on a signup form after the subscriber enters their email address and name, the signup page should reload within the same tab wi ...

Is there a way to convert this asynchronous function into a synchronous one so that it returns the value immediately

When it comes to making a Nodejs/Javascript method synchronous, there are several solutions offered by the community. Some suggest using libraries like async and fibrous, but these involve wrapping functions externally. However, I am in search of a soluti ...

Ways to adjust a specific div within an ng repeat using the value from JSON in AngularJS

When I select a different option from the dropdown menu, such as cities or states, the values are populated from a JSON file. My specific requirement is to hide a button only when the value 'No data' is populated upon changing the dropdown select ...

Utilize a React Switch Toggle feature to mark items as completed or not on your to-do list

Currently, I am utilizing the Switch Material UI Component to filter tasks in my list between completed and not completed statuses. You can view the demonstration on codesandbox The issue I'm facing is that once I toggle a task as completed, I am un ...

I'm currently utilizing lint in my Angular 2+ project. Is there a way to arrange the constructor parameters in alphabetical order

I am struggling to organize the constructor parameters in TypeScript while using TSLINT with Angular9. I am looking for a rule similar to member-ordering that can help me sort them effectively. constructor( // Sort these private readonly router: R ...

The asynchronous callbacks or promises executing independently of protractor/webdriver's knowledge

Could a log like this actually exist? 07-<...>.js ... Stacktrace: [31m[31mError: Failed expectation[31m [31m at [object Object].<anonymous> (...06-....js)[31m[31m[22m[39m It seems that something is failing in file -06- while I am processin ...

Tips for creating a div that gracefully fades out its background image when hovered over, while keeping the internal content unaffected

I am looking to create a hover effect on a div element that has a background-color, background-image, and text. What I want is for the background-image to slowly disappear when the div is hovered over, while keeping the text and background color visible. I ...

Using Webpack postcss prefixer with Vue CLI 3

As I work on implementing Bulma CSS in my project using Vue CLI 3, I encounter the need to prefix the classes with webpack. While I found an example of this process, adapting it from a webpack config to vue.config.js poses some challenges. Here is the ini ...

Generate a link that can easily be shared after the content has loaded using

One feature on my website involves a content container that displays different information based on which list item is clicked (such as news, videos, blogs, etc.). This functionality is achieved by using jQuery's load method to bring in html snippets ...

Running multiple JavaScript servers simultaneously can be achieved by utilizing specific tools and

Currently, I am working on developing a Discord bot and have encountered some issues along the way that all required the same solution. The fix involved running separate batch files instead of running everything in my main file (index.js). I opted to use n ...

Enhancing the node module of a subpackage within Lerna: A step-by-step guide

I recently integrated lerna into my workflow to streamline the installation of all node modules for multiple sub packages with just one command. Currently, I'm only utilizing the lerna bootstrap feature. Here's a snippet from my lerna.json: { & ...

Step-by-step guide on integrating a JSON array fetched via Ajax from a Django/Python view with DataTable

Being a new developer, I am embarking on my first professional project using Django. My main challenge lies in loading data that I have extracted from the models.py into a DataTable within my view.py file. Below is the snippet of my code. Brief Overview ...

Storing items in localStorage in the same order they were added

I am having an issue with sorting localStorage items by the order they were added. Despite my code working to add items to the localStorage array and display them as HTML, I am encountering a problem with the order of the items. When I add a 3rd item to t ...

The generation of the page fails due to the absence of defined data

Every time I try to start my server, the error message pops up saying 'data is not defined', even though I have already defined the data content. export default class App extends Component { data = [ { key: "john", val ...

Received undefined response from Axios.get() request

While working with the code below, I encountered an issue. The axios get request from await axios.get('/products/api') is functioning properly and I can see the data in the console. However, for await axios.get('/users/api'), 'Unde ...

Error: Attempting to access the 'getProvider' property of an undefined variable

I am encountering an error that says "property of undefined (reading getProvider)" while deploying my function to Firebase. I am currently trying to figure out how to obtain the auth instance. When I attempt to use firebase.auth, it results in another er ...

When the page initially loads, the block appears on top of the upper block and remains in place after the page is refreshed

Upon initial loading, the block appears on top of another block but remains fixed upon page refresh. The same issue occurs in the mobile version of the site and occasionally displays correctly. The website is built on WordPress and optimized using Page Spe ...