简体   繁体   English

Javascript冒泡与对象的数组

[英]Javascript bubble sort of an array with objects

beginner here! 初学者来了!

Recently stumbled upon a problem. 最近偶然发现了一个问题。 Basically, the program needs to sort an array of objects by one of their fields without actually using the sort function. 基本上,程序需要通过其中一个字段对对象数组进行排序,而不实际使用sort函数。 I've tried this code using bubble sort algorithm, but it doesn't seem to be working: 我已经使用冒泡排序算法尝试了这个代码,但它似乎没有工作:

var arrayOfPeople = [
    {name: "Rick", age: 30, place: 2},
    {name: "Alan", age: 25, place: 1},
    {name: "Joe", age: 40, place: 4},
    {name: "Dave", age: 35, place: 3}
];


function bubbleSort(a,par)
{
    var swapped;

    do {
        swapped = false;

        for (var i = 0; i < a.length - 1; i++) {
            if (a[i].par > a[i + 1].par) {
                var temp = a[i];

                a[i] = a[i + 1];
                a[i + 1] = temp;

                swapped = true;
            }
        }
    } while (swapped);
}


bubbleSort(arrayOfPeople,'age');

for (i = 0; i < arrayOfPeople.length; i++) {
    console.log(arrayOfPeople[i]);
}

My guess is that I'm doing something wrong syntax-wise. 我的猜测是我在语法方面做错了。 Will appreciate any feedback. 将不胜感激任何反馈。

The only problem was that you were not using the "par" argument correctly. 唯一的问题是你没有正确使用“par”参数。 The obj.prop syntax will always try to look for property named "prop" so to have it dynamic you need to use square brackets eg obj["prop"] which can get variable instead of "prop". obj.prop语法将始终尝试查找名为“prop”的属性,因此要使其具有动态性,您需要使用方括号,例如obj [“prop”],它可以获取变量而不是“prop”。

You didn't get any errors as a[i].par and a[i+1].par both returned undefined which can be compared to itself. 你没有得到任何错误,因为a[i].para[i+1].par都返回undefined ,可以与自身进行比较。 (hence a[i].par > a[i+1].par always returns false) (因此a[i].par > a[i+1].par总是返回false)

Here is revised code that works: 以下是修改后的代码:

function bubbleSort(a, par)
{
    var swapped;
    do {
        swapped = false;
        for (var i = 0; i < a.length - 1; i++) {
            if (a[i][par] > a[i + 1][par]) {
                var temp = a[i];
                a[i] = a[i + 1];
                a[i + 1] = temp;
                swapped = true;
            }
        }
    } while (swapped);
}


bubbleSort(arrayOfPeople, 'age');

for (i = 0; i < arrayOfPeople.length; i++) {
   console.log(arrayOfPeople[i]);
}

Live test case . 现场测试案例

Worth to mention in this context, that the function changing the actual object (array in this case) is not a trivial thing. 值得一提的是,在这种情况下,改变实际对象的函数(在这种情况下是数组)并不是一件小事。 To learn more what is passed by value and what is passed by reference take a look in this excellent question: Is JavaScript a pass-by-reference or pass-by-value language? 要了解更多通过值传递的内容以及通过引用传递的内容,请查看以下优秀问题: JavaScript是通过引用传递还是按值传递语言?

使用内置数组排序功能:

arrayOfPeople.sort(function(a,b) {return a.age-b.age;});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM