JavaScript sorted arrays are an efficient way to keep data

In my dataset, I have an array of objects representing various products. Each product object includes a field called ratingReviews and another field called price, which can either be a string or an object. If the price is represented as an object, it contains a field named newUan to hold the new price.

The ratingReviews field consists of a number followed by a word, while the price or newUan field contains a human-readable number followed by a currency name in the format of space-delineated values.

I am looking to implement two functions that sort the products based on:

  1. The numeric value in the ratingReviews field.
  2. The numeric value in the price field, preferring price.newUan if available.

--

I already know how to sort based on ratingReviews:

const sortedByRating = () => {
  return products.sort((a, b) => {
    return parseFloat(b.ratingReviews) - parseFloat(a.ratingReviews)
  })
}

However, I need assistance sorting based on either price or price.newUan depending on what's provided. Could you please provide me with guidance on that?

For reference, here is a sample of my data:

const products = [
      // Sample product objects
    ]

Answer №1

function sortByRating() {
    const copyList = [...products];
    return copyList.sort((itemA, itemB) => {
        const [ratingItemA] = itemA.ratingReviews.split(' ');
        const [ratingItemB] = itemB.ratingReviews.split(' ');
        return ratingItemB - ratingItemA;
    });
};

function sortByPrice() {
    const copyList = [...products];
    return copyList.sort((itemA, itemB) => {
        let priceItemA = itemA.price.newUan ? itemA.price.newUan.replace(/\s+/g, '') : itemA.price.replace(/\s+/g, '');
        priceItemA = priceItemA.slice(0, priceItemA.length - 3);
        let priceItemB = itemB.price.newUan ? itemB.price.newUan.replace(/\s+/g, '') : itemB.price.replace(/\s+/g, '');
        priceItemB = priceItemB.slice(0, priceItemB.length - 3);
        return priceItemB - priceItemA;
    });
};

Answer №2

const sortByPrice = () => products.sort((a, b) => {
  if (a.price.newUan && b.price.newUan) return parseFloat(b.price.newUan) - parseFloat(a.price.newUan);
  if (a.price.newUan) return parseFloat(b.price) - parseFloat(a.price.newUan);
  if (b.price.newUan) return parseFloat(b.price.newUan) - parseFloat(a.price);
  return parseFloat(b.price) - parseFloat(a.price);
});

The use of the return statement helps to control the flow of execution within the function.

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

Manipulating Angular and Typescript to utilize the method's parameter value as a JavaScript object's value

I am currently working with Ionic, Angular, and Typescript, attempting to dynamically set the value of a location based on the parameter passed from a method. Here is the relevant code snippet: async fileWrite(location) { try { const result = a ...

Adjust the height of a DIV element using Jquery Resizable to a minimum height of 1px, smaller than its default value

Having an issue with the Jquery UI Resizable functionality. I've implemented Jquery resizable to adjust a div's width and height dynamically. It's been working well, but I'm encountering a problem when attempting to decrease the height ...

Error message: The Bootstrap .dropdown() method failed because it encountered an "Uncaught TypeError: undefined is not a function"

I've encountered an issue that seems to be a bit different from what others have experienced. Despite trying various solutions, I still can't seem to fix it. I suspect it might have something to do with how I'm importing my plugins. The erro ...

perform an action in PHP when a button is clicked

I'm currently developing a PHP admin panel that displays a list of users in an HTML table format. Each row in the table includes a button that allows the admin to send a notification to the selected user. Below is the code I used to create and displa ...

Creating a unique array of non-repeating numbers in ES6:

Looking to create an array of unique random numbers in ES6 without any repeats. Currently, my function is generating an array of random numbers that are repeating: winArray = [...Array(6)].map(() => Math.floor(Math.random() * 53)); Here is a non-ES6 ...

What are the steps for displaying multiple input fields using the onchange method?

$(document).on("change","#noofpack",function(){ count = $(this).val(); for(i=1;i<=count;i++){ $("#packageDiv").html('<input type="text" class="form-control" name="unit_price[]" placeholder="Unit Price" required="">'); ...

What is the best way to transfer the value of a slider from jQuery or JavaScript to a Python Flask application

Trying to implement a round slider that displays its value on the client-side webpage. Whenever the user adjusts the slider, the updated value needs to be sent to the server using Python Flask as the backend. I attempted to achieve this using jQuery and Aj ...

unable to update database using jquery ajax

Hello everyone, this is my first time posting on Stackoverflow! I am facing an issue while trying to run an "Insert" query using Jquery's $.ajax function. Upon checking the network tab on Chrome Dev Tools, it seems like my file is being loaded but th ...

Bootstrap Modal for WooCommerce

I'm facing an issue while trying to create a modal window using woocommerce variables ($product). The problem lies in the placement of my modal and accessing the correct product id. Here is the code snippet I've been working on. Unfortunately, i ...

How can you optimize the uploading time and bandwidth by a factor of 1/3 when the output of toDataURL is in base64 format?

The purpose of the code snippet below is to compress a 2 MB JPG file to a 500 KB file, and then upload it to a server upon submitting a <form>. By importing an image from a JPG file into a canvas and exporting it using toDataURL, the following JavaS ...

How can I display the value entered in a text input field when using ajax upload?

Is there a way to display the value of an input type text when using ajax for file upload? I have successfully implemented code to upload files to a directory called attachments_files, but I am facing an issue. How can I retrieve and echo the value from i ...

The URL provided by window.location is not accurate

I'm facing an issue with the code window.history.pushState("", "title", myCtxURLVersion); which is supposed to change the current URL of the page. However, when I implement this code, the URL displayed is incorrect. For example, even though the brows ...

Issue with create-react-app and express server not displaying correctly in Internet Explorer

My application functions perfectly with Chrome and Safari. It utilizes React for the front-end and Express for the back-end. However, when I try to open it in Internet Explorer, all I see is a blank white page. Additionally, I encounter this error message: ...

Entwine words around an immovable partition

Is it possible to create an HTML element that remains fixed in place even as the content on the webpage changes, with everything else adjusting around it? I am looking to add a continuous line that spans across a dynamic webpage. No matter how much conten ...

Error code 0 occurs in jQuery AJAX when there is an issue with the communication between the client

Currently delving into the world of ASP.NET and wanted to create a basic website utilizing ajax to retrieve a simple string from the server. Upon running the ajax request, an error message pops up stating An error occurred: 0 error Here's a glimpse ...

typescript: the modules with relational paths could not be located

As part of a migration process, I am currently converting code from JavaScript to TypeScript. In one of my files 'abc.ts', I need to import the 'xyz.css' file, which is located in the same directory. However, when I try to import it usi ...

The drawing library (Google Maps) failed to load

I am looking to integrate drawing mode into Google Maps for my project. Below is the code snippet from my View: <!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <me ...

I'm facing issues with Angular commands not functioning properly even after installing the Angular CLI and configuring the

Every time I attempt to create a new project using Angular CLI by typing: ng n app I encounter the following error message: C:\Users\Venkateshwarn M\AppData\Roaming\npm\node_modules\@angular\cli\bin\ng: ...

Modifying all occurrences of a specified string in an object (or array) - JavaScript

Is there a more efficient way to search through and replace all instances of a given string in a JavaScript object with unknown depth and properties? Check out this method, but is it the most optimal solution? var obj = { 'a' : 'The foo ...

Get the docx file generated with Flask and VueJS

I've been grappling with the challenge of downloading a docx file in VueJS. Initially, I attempted to generate the file on the frontend, but it kept getting corrupted. To solve this issue, I resorted to using Flask to create the docx file, which worke ...