简体   繁体   English

Javascript自定义数组按数组排序

[英]Javascript custom array sort by array

I currently have this function which sort an array alphabetically. 我目前有此功能,按字母顺序对数组进行排序。

function compare(a,b) {
    if (a.subtitle < b.subtitle)
        return -1;
    if (a.subtitle > b.subtitle)
        return 1;
        return 0;
}

I need a similar function that sorts the array by another array. 我需要一个类似的函数,该函数按另一个数组对数组进行排序。 I tried writing it myself but i couldn't get my head around it so i ended up with nothing. 我尝试自己写它,但是我无法理解,所以我一无所有。

Example: 例:

I need array1 to be sorted depending on where that item is in array2. 我需要根据该项目在array2中的位置进行排序。

Array1 = ['quick','fox','the','brown'];
Array2 = ['the','quick','brown','fox'];

There is probably an easy answer that i am not seeing. 我可能没有看到一个简单的答案。

Edit: 编辑:

Also any items that are in array1 that aren't in array 2 can just be tacked onto the end in no particular order or alphabetically whatever is easier. 同样,数组1中未出现在数组2中的任何项都可以不按特定顺序或按字母顺序(更容易)固定在最后。

Try this: 尝试这个:

function compare(a,b, compareArray) {
    if ((compareArray.indexOf(a) != -1 && compareArray.indexOf(a) < compareArray.indexOf(b))
         ||  compareArray.indexOf(b) == -1)
        return -1;
    if ((compareArray.indexOf(a) > compareArray.indexOf(b))
         || compareArray.indexOf(a) == -1)
        return 1;
        return 0;
}

http://jsfiddle.net/AMSDE/ http://jsfiddle.net/AMSDE/

var Array1 = ['quick', 'fox', 'the', 'brown', 'abc']; //the array to be sorted
var Array2 = ['the', 'quick', 'brown', 'fox'];
var sortedAry = [];

for (var i = 0; i < Array2.length; i++) {
var index = Array1.indexOf(Array2[i]);
if (index !== -1) {
    console.log(index);
    sortedAry.push(Array2[i]);
    Array1.splice(index, 1);
}
}

for (var j = 0; j < Array1.length; j++) {
sortedAry.push(Array1[j]);
}

console.log(sortedAry);

I ran across the need to do the same thing today, this was my solution: 今天,我遇到了要做相同事情的需要,这就是我的解决方案:

var arr = [".", 5359, 1, 2, 3, 4, 6, 9, 15];
var priorities = [3, '.', 1, 4, 15, 9, 2, 6];

var resultArr = arr.filter( function(arrElement) { return priorities.indexOf(arrElement) >= 0 })
    .sort( function (a,b) { return priorities.indexOf(a) - priorities.indexOf(b) })
    .concat( arr.filter( function(arrElement) { return priorities.indexOf(arrElement) < 0})
);

console.log(resultArr.join(""));

console: 3.14159265359 控制台: 3.14159265359

jsfiddle based on @rps's answer jsfiddle基于@rps的答案

Basically, it picks out the elements that we have a preferred order for, sorts those, then appends the elements that we had no order preference for. 基本上,它挑选出我们有优先顺序的元素,对它们进行排序,然后附加我们没有优先顺序的元素。 As a bonus (at least for my use case), the sorting is non-destructive to the order of arr . 作为奖励(至少对于我的用例而言),排序对arr的顺序无损。

I'm not sure if this is better or worse, but I know I loathe for loops. 我不知道这是好还是坏,但我知道我讨厌for循环。 :) :)

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

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