简体   繁体   English

javascript排序2D数组使数组重复

[英]javascript sorting 2D array makes duplicates in my array

I am trying to sort my 2D array according to column 3. when I sort it with sort function, all the array members become duplicates of one member of the original array. 我试图根据第3列对2D数组进行排序。当我使用sort函数对其进行排序时,所有数组成员都将成为原始数组的一个成员的副本。

so for example; 例如

my original array: 我原来的数组:

[12, AAA, eee, 5]
[58, BBB, zzz, 3]
[28, CCC, ddd, 6]
[18, DDD, fff, 9]

I want it to become : 我希望它成为:

[18, DDD, fff, 9]
[28, CCC, ddd, 6]
[12, AAA, eee, 5]
[58, BBB, zzz, 3]

I use the code : 我使用代码:

function sortByColumn(a, colIndex){

    a.sort(sortFunctionq);

    function sortFunctionq(a, b) {
        if (a[colIndex] === b[colIndex]) {
            return 0;
        }
        else {
            return (a[colIndex] > b[colIndex]) ? -1 : 1;
        }
    }

    return a;
}

var sorted_a = new Array(15);
sorted_a = sortByColumn(arr, 3);

now the array becomes: 现在数组变成:

[18, DDD, fff, 9]
[18, DDD, fff, 9]
[18, DDD, fff, 9]
[18, DDD, fff, 9]

I am using javascript on Samsung Gear watch. 我在Samsung Gear手表上使用javascript。 maybe it does not support the "sort" function correctly. 也许它不正确地支持“排序”功能。 is there a way to sort 2D array without using sort function ? 有没有一种方法可以不使用sort函数对2D数组进行排序?


final code is: 最终代码是:

    var sorted_a = new Array(15);
    sorted_a = sortByColumn(arrx, 3);
    arrx= sorted_a;

function bubbleSort(a, fCompare) {
    if( a.length < 2)   {return a;}
    for( var length = a.length-1; length; --length) {
        var noSwaps = true;
        var temp;
        for(var c=0; c<length; ++c) {
            if( fCompare( a[c], a[c+1]) > 0) {
                temp = a[c+1];
                a[c+1] = a[c];
                a[c] = temp;
                noSwaps = false;
            }
        }
        if( noSwaps) {break;}
    }
}

function sortByColumn(a, colIndex){
    function sortFunctionq(a, b) {
        if (a[colIndex] === b[colIndex]) {
            return 0;
        }
        else {
            return (a[colIndex] > b[colIndex]) ? -1 : 1;
        }
    }
    //return bubbleSort(a, sortFunctionq);
    return bubbleSort(a.slice(), sortFunctionq);
}

but now nothing is available in the array. 但是现在数组中没有任何可用的东西。

for those who ask: if I remove the sort function and use arrx as it is, I can reach 2D array elements with arrx[1][1] but with the code above arrx[1][1] returns null. 对于那些问:如果我删除排序函数并按原样使用arrx,则可以使用arrx [1] [1]到达2D数组元素,但是使用上面的代码arrx [1] [1]返回null。


I changed it a bit and now it seems to work. 我对其进行了一些更改,现在似乎可以使用了。 But now I need to remove duplicates as well. 但是现在我也需要删除重复项。 How can I do that ? 我怎样才能做到这一点 ?

current code: 当前代码:

    var arrx = new Array(50);
    for (var j = 0; j<50; j++){
        arrx[j] = arr[j].split("|+");
    }
    var arry = new Array(50);
    arry = bubbleSort(arrx);

function bubbleSort(a) {
    for( var r = 49; r >= 0; --r) {
        var noSwaps = true;
        var temp = new Array(50);
        for(var c=0; c<r; ++c) {
            if (a[c][3] < a[c+1][3]) {
                temp = a[c+1];
                a[c+1] = a[c];
                a[c] = temp;
                noSwaps = false;
            }
        }
        if( noSwaps) {break;}
    }
    return a;
}

The direct answer to you question is "yes, it is possible to sort an array without using the array's sort method". 问题的直接答案是“是的,可以在不使用数组的sort方法的情况下对数组进行排序”。 A simple example using bubble sort: 一个使用冒泡排序的简单示例:

 function bubbleSort(a, fCompare) { if( a.length < 2) return a; for( var length = a.length-1; length; --length) { var noSwaps = true; var temp; for( i=0; i<length; ++i) { if( fCompare( a[i], a[i+1]) > 0) { temp = a[i+1]; a[i+1] = a[i]; a[i] = temp; noSwaps = false; } } if( noSwaps) break; } } function sortByColumn(a, colIndex){ function sortFunctionq(a, b) { if (a[colIndex] === b[colIndex]) { return 0; } else { return (a[colIndex] > b[colIndex]) ? -1 : 1; } } return bubbleSort(a, sortFunctionq); } var a = [ [12, 'AAA', 'eee', 5], [58, 'BBB', 'zzz', 3], [28, 'CCC', 'ddd', 6], [18, 'DDD', 'fff', 9], ]; var sortedA = sortByColumn(a,2) // updates a in-place, as well console.log( JSON.stringify(sortedA)) 

However 然而

Note that both the sort method of an array and the bubbleSort above change the order of elements in the array being sorted, without creating a shallow copy of the array. 请注意,数组的sort方法和上面的bubbleSort更改要排序的数组中元素的顺序,而不会创建该数组的浅表副本。 While bubbleSort may show the Samsung JS engine has a problem, more than likely it will not and produce the same result. 尽管bubbleSort可能表明Samsung JS引擎有问题,但很有可能不会并产生相同的结果。

Because sorting sorts the array in place, you may wish to check if creating a shallow copy of it before sorting solves the problem. 由于排序对数组进行了排序,因此您可能希望在排序解决问题之前检查是否创建它的浅表副本。 EG by replacing the return statement in the example with EG通过将示例中的return语句替换为

return a.slice().sort(functionq) // OR
return bubbleSort(a.slice(), functionq)


Debugging notes: 调试注意事项:

  1. JavaScript arrays are objects. JavaScript数组是对象。 The value of an object variable is a reference of some kind used by the JavaScript engine to access object properties. 对象变量的值是JavaScript引擎用来访问对象属性的某种引用。 The reference could be a memory pointer or some other value used by the engine to access object data. 引用可以是内存指针或引擎用于访问对象数据的其他某个值。 When you assign an object to a variable, its existing content is overwritten. 将对象分配给变量时,其现有内容将被覆盖。 If you assign the same object value to two variables, they hold the same refernce value and refer to the same set of object data. 如果将相同的对象值分配给两个变量,则它们将具有相同的引用值并引用相同的对象数据集。

     var arry = new Array(50); arry = bubbleSort(arrx); 

    unnecessarily creates a new Array, because the new Array value is overwritten in the second line. 由于新的Array值在第二行中被覆盖,因此不必要地创建了一个新的Array。 It can be simplified as 可以简化为

     var arry = bubbleSort( arrx). 

    Note that JavaScript arrays can grow and shrink and do not have some pre-allocated length. 请注意,JavaScript数组可以增长和收缩,并且没有预先分配的长度。

  2. Both the bubble sort code and the inbuilt array sort method (inherited by an array instance from the Array.prototype object, and documented on MDN under Array.prototype.sort ) sort the array in place and return an object reference to the array being sorted. 冒泡排序代码和内置数组sort方法(由Array.prototype对象的数组实例继承,并记录在MDN的Array.prototype.sort下)均对数组进行排序,并将对象引用返回到要排序的数组。 After

     arry = bubbleSort(arrx); // OR arry = arrx.sort(sortFunction) 

    the value of arry is the same as arrx . 的值arry相同arrx If you want to make a copy of the array that is immune to arrx modificatioms of first dimension values, make a shallow copy of the input array before sorting: 如果要复制不受第一维值的arrx修改影响的数组,请在排序之前对输入数组进行浅表复制:

     arry = bubbleSort(arrx.slice()); 

    If you want to make a copy that is immune to modifications to either dimension value then make a shallow copy of both dimensions' arrays as for example: 如果要创建一个不受任何一个维值修改影响的副本,则可以对两个维的数组进行浅表复制,例如:

     arry = bubbleSort( arrx.map(element => element.slice()) 

    This creates new arrays from both dimensions of arrx before sorting. arrx在排序之前从arrx两个维度创建新的数组。

If you are still getting duplicate entries after this you will need to find out where in the code the duplicates are being assigned. 如果您在此之后仍收到重复的条目,则需要找出在代码中重复的位置。


Tip 小费

Check there are no typos in conditional tests that use = (the assignment operator) instead of == or === operators to test for equality. 检查在使用= (赋值运算符)而不是=====运算符的条件测试中是否没有错别字来测试是否相等。 This is a good way of inadvertently assigning values to something that was not meant to be changed. 这是一种无意中将值分配给不希望更改的对象的好方法。

All you need to change is to return the sorted array. 您需要更改的只是返回排序后的数组。

 const data = [ [12, 'AAA', 'eee', 5], [58, 'BBB', 'zzz', 3], [28, 'CCC', 'ddd', 6], [18, 'DDD', 'fff', 9] ]; function sortByColumn(a, colIndex){ function sortFunctionq(a, b) { if (a[colIndex] === b[colIndex]) { return 0; } else { return (a[colIndex] > b[colIndex]) ? -1 : 1; } } return a.sort(sortFunctionq); //^^^^^^^^^^^^^^^^^^^^^^^^^^^ } const result = sortByColumn(data, 3); console.log(result); 

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

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