我有一个数组和一个正则表达式:
var array = ['dog and cat', 'cat and dog', 'horse', 'snake is dangerous'];
var regex = /^((dog)?(snake)?(horse)?(cat)?)/g;
//final output:
var array = ['dog and cat', 'snake is dangerous', 'horse', 'cat and dog'];
如何命令此数组具有所需效果?
修改: 我发明了一个解决方案:
var array = ['dog','cat']; var re-order = [];
i=0;
while(array[i]){
if(string.test(array[i])){
re-order[i] = array[i];
}
i++;
}
答案 0 :(得分:1)
试试这个:
function getSortValue(str) {
return sortOrder.reduce(
(val, key, idx) => {
let temp = str.substr(0,key.length);
return (temp === key) ? idx+1 : val;
}, 0
);
}
function sortMe(a,b) {
var a1 = getSortValue(a);
var b1 = getSortValue(b);
if (a1 < b1) {
return -1;
} else if (a1 > b1) {
return 1;
}
if (a < b) {
return -1;
} else if (a > b) {
return 1;
}
return 0;
}
var sortOrder = ['dog','snake','horse','cat'];
var array = ['dog and cat', 'cat and dog', 'horse', 'snake is dangerous', 'dog and bird', 'cat and fish'];
console.log(array);
array.sort(sortMe)
console.log(array);
在:
["dog and cat", "cat and dog", "horse", "snake is dangerous", "dog and bird", "cat and fish"]
后:
["dog and bird", "dog and cat", "snake is dangerous", "horse", "cat and dog", "cat and fish"]
函数getSortValue
根据字符串和首选顺序将字符串转换为索引。然后函数sortMe
根据这些值进行排序,如果值相同,则对我的字符串比较进行排序。
此代码不会检查
dog
vsdogs
或dogfood
等完整字词,但这些字词应由sortMe
函数的字符串比较部分处理