我遇到了数组排序序列的问题。需要你的帮助以获得理想的结果。
var a = [0, 1, 2, 3, 4, 5, 6, 77, 7, 8, 9, 10, 11, 12, 35, 36, 43, 51, 72, 89, 95, 100];
var b = [6,5,7,8,0,800,46,1,2,3,12,47,100,95];
var c = [];
for (var i = 0; i <= (a.length) - 1; i++) {
var res = b.indexOf(a[i]);
if (res > -1) {
c.push(a[i]);
}
}
document.write(c);
// I need same sequence of array B in reponse
// Desired Result
// 6,5,7,8,0,1,2,3,12,100,95
答案 0 :(得分:4)
迭代数组b
而不是a
:
var a = [0, 1, 2, 3, 4, 5, 6, 77, 7, 8, 9, 10, 11, 12, 35, 36, 43, 51, 72, 89, 95, 100];
var b = [6,5,7,8,0,800,46,1,2,3,12,47,100,95];
var c = [];
for (var i = 0; i < b.length; i++) {
var res = a.indexOf(b[i]);
if (res > -1) {
c.push(b[i]);
}
}
console.log(c.join(','));
更实用的解决方案是在b:
上使用Array#filter
var a = [0, 1, 2, 3, 4, 5, 6, 77, 7, 8, 9, 10, 11, 12, 35, 36, 43, 51, 72, 89, 95, 100];
var b = [6,5,7,8,0,800,46,1,2,3,12,47,100,95];
var c = b.filter(function(n) {
return a.indexOf(n) !== -1;
});
console.log(c.join(','));