Unexpected outcome when converting a while loop to a .forEach statement

Exploring a practical demonstration of sorting an array of objects based on multiple properties, the code implementation involves a while loop (refer to students1 in the snippet below). I attempted to streamline this process by using .forEach, but encountered a discrepancy in the output compared to the original while loop. What might have caused this divergence when refactoring with .forEach?

const students = [
    {
        firstName: 'John',
        lastName: 'Appletree',
        grade: 12
    },
    {
        firstName: 'Mighty',
        lastName: 'Peachtree',
        grade: 10
    },
    {
        firstName: 'Kim',
        lastName: 'Appletree',
        grade: 11
    },
    {
        firstName: 'Shooter',
        lastName: 'Appletree',
        grade: 12
    },
    {
        firstName: 'Peter',
        lastName: 'Peachtree',
        grade: 12
    }
];

const sortBy = [
    {
      prop:'grade',
      direction: -1
    },
    {
      prop:'lastName',
      direction: 1
    }
];

const students1 = JSON.parse(JSON.stringify(students));
const students2 = JSON.parse(JSON.stringify(students));

students1.sort((a, b) => {
  let i = 0, result = 0;
  while (i < sortBy.length && result === 0) {
    const prop = sortBy[i].prop;
    const direction = sortBy[i].direction;
    result = direction *
        (
             a[prop].toString() < b[prop].toString() ? -1 :
            (a[prop].toString() > b[prop].toString() ? 1 : 0)
        );
    i++;
  }
  return result;
});

students2.sort((a, b) => {
  let result = 0;
  sortBy.forEach(o => {
    result = o.direction *
    (
         a[o.prop].toString() < b[o.prop].toString() ? -1 :
        (a[o.prop].toString() > b[o.prop].toString() ? 1 : 0)
    );
  });
  return result;
});

console.log(students);
console.log('one', students1);
console.log('two', students2);

Answer №1

There is a difference between your forEach and while loops. If you were to remove the extra condition of result === 0 in the while loop, it would be equivalent to the forEach loop.

Answer №2

It seems like there is an issue with the implementation of the condition in the while loop:

const students = [
    {
        firstName: 'John',
        lastName: 'Appletree',
        grade: 12
    },
    {
        firstName: 'Mighty',
        lastName: 'Peachtree',
        grade: 10
    },
    {
        firstName: 'Kim',
        lastName: 'Appletree',
        grade: 11
    },
    {
        firstName: 'Shooter',
        lastName: 'Appletree',
        grade: 12
    },
    {
        firstName: 'Peter',
        lastName: 'Peachtree',
        grade: 12
    }
];

const sortBy = [
    {
      prop:'grade',
      direction: -1
    },
    {
      prop:'lastName',
      direction: 1
    }
];

const students1 = JSON.parse(JSON.stringify(students));
const students2 = JSON.parse(JSON.stringify(students));

students1.sort((a, b) => {
  let i = 0, result = 0;
  while (i < sortBy.length && result === 0) {
    const prop = sortBy[i].prop;
    const direction = sortBy[i].direction;
    result = direction *
        (
             a[prop].toString() < b[prop].toString() ? -1 :
            (a[prop].toString() > b[prop].toString() ? 1 : 0)
        );
    i++;
  }
  return result;
});

students2.sort((a, b) => {
  let result = 0;
  sortBy.forEach(o => {
    if (result !== 0) return;
    result = o.direction *
    (
         a[o.prop].toString() < b[o.prop].toString() ? -1 :
        (a[o.prop].toString() > b[o.prop].toString() ? 1 : 0)
    );
  });
  return result;
});

console.log(students);
console.log('one', students1);
console.log('two', students2);

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 could be causing the issue with my validation for alphabetical input?

I am currently working on a registration form that only accepts alphabetical input. However, I am facing an issue where my error message appears regardless of whether I input an alphabetical or special character. According to my understanding, the code sho ...

Convert Python strings into HTML JavaScript blocks using Jinja2

Having trouble passing a string to an HTML page in the "<script>" block. I am currently using Python, Flask, and Jinja2. Python code: def foo(): return myString #"[{title: 'Treino 7-Corrida',start: '2015-12-08',color: '#d ...

Make a quick call to the next function within the error handling module for a

Currently, I am facing an issue while trying to call the next function within the error handler of my node + express js application. In each controller, I have a middleware known as render which is invoked by calling next, and I wish to achieve the same f ...

It appears as though the promise will never come to fruition

I am currently developing an application that is designed to search for subdomains related to a specific domain and store them in a database. The application retrieves data from crt.sh and threatcrowd. One of the functions within the application parses th ...

Inquiring about Vue component prop defaults and detecting when a user has not assigned a value

1. I am looking for a way to set a default value for a component prop in Vue 2. Take, for example, a basic movies component that can be utilized like this: <movies year="2016"><movies> Vue.component('movies', { props: ['yea ...

Detecting whether a browser is capable of supporting dark mode

One method to determine if dark mode is active is by using prefers-color-scheme: dark: const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches; Is there a way to detect if a browser supports dark mode as well? (By "supports ...

Troubleshooting Cache Problems in Express.js 4.0 during Development

Recently, I created a fresh express.js application using the express-generator. However, when I attempt to make modifications, none of them seem to reflect when I refresh the browser. I have tried various solutions found online, including: Disabling Chr ...

What is the best way to refresh the script located within the head tag of an index.html file in an Angular

I've been looking for solutions, but I can't seem to find one. In my index.html file, I've placed some script within the head tag (even above the </body> tag) and included a $(document).ready function. The issue I'm facing is th ...

Browsing through an array of objects in PHP

Currently working on creating an array of objects using jQuery. var selected_tests = $("#selected_tests").find("tr"); jsonLab = []; $.each(selected_tests, function() { jsonLab.push({ test: ($(this).children()).eq(0).text(), amount: ($(this).chil ...

Customizing App (directory) elements in next.js 13

Imagine having this directory organization: https://i.stack.imgur.com/Hd5gu.png Is there a method for loading the component from the custom folder instead of the default one in the app folder? In case the custom folder does not have that component, can t ...

Create a new canvas for each iteration of a Vue.JS template loop

I'm having trouble figuring out how to initialize a local "signaturePad" canvas for each loop or required signature. Additionally, I am interested in binding "dataURL" to signaturePad.toDataURL("image/jpg"). This means displaying the dataURI for ever ...

When the user clicks, I plan to switch the audio source

I am looking to update the audio source when a button is clicked, but I am having trouble getting it to work. image description data() { return { audioSrc: '' } }, methods: { setActiveAudio(item) { this.$refs.audioE ...

"Sequelize will pause and wait for the loop to finish before executing the

As someone with a background in PHP, I'm finding the concept of callbacks a bit challenging to grasp. Essentially, I need to retrieve some rows and then iterate through them to compare against another model (in a different database). However, I want ...

Sustain information across two pages using Next.js

Recently, I have been considering reorganizing my Next.js webapp to allocate different pages for handling various screens. Currently, I have a component that manages multiple states to determine the screen being displayed. Within the jsx section, I utilize ...

Interactive image map with hover effects and external image swapping placed beyond the container

I've encountered a problem with a responsive image map and rollovers. Using Matt Stow's responsive image jQuery plugin ensures that coordinates are responsive, and clicking on an area brings up Lightview as expected. However, the issue arises whe ...

changing the name of a variable within ng-include

Here is some important HTML code: <ng-include src="'app/views/order.html'"></ng-include> Within the scope of this ng-include, there is a variable called trade. The structure of the trade variable is as follows: var trade = { or ...

Creating interactive web pages for scheduling tasks

I'm struggling with how to implement this concept. Imagine I have a School website that features a schedule page for 30 upcoming courses. When a course is clicked, it should lead to a new page displaying specific information about that course (such a ...

Gulp- Ensuring the latest versions of your javascript files

I have implemented bundling and minification for my JavaScript files using gulp. What I am aiming to achieve is that whenever I make a change in any of my files and run gulp, a new bundled and minified file with a version number is generated. For example: ...

Configuring the array interval in an Angular application

I'm facing an issue while attempting to use the setInterval() function to update text for the user every 3 seconds. My attempt at looping with a for loop has not been successful - I only see 'test 03' and nothing else. I'm struggling ...

JavaScript code to change an array into a stringified format

I have encountered a challenge with transforming an array. The original array looks like this: array = [ { "name": "name", "value": "Olá" }, { "name": "age" ...