我有2组数组
var A = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"];
var B = ["B", "J", "A", "C", "G"];
现在我必须从 var B
获取一个值这是 var A
中最高和最低索引,就是J
& A
我必须找出J
& A
在 var B
通过JavaScript编程
这是我的代码,可以正常使用上面的示例 var A
& B
但要符合我的实际要求
var C = ["SX", "S", "M", "L", "XL", "XXL", "ML", "LL", "XLL", "MK", "LK", "XLK", "MS", "LS", "XLS"];
var D = ["XLL", "XXL", "XLK"];
var A = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"];
var B = ["B", "J", "A", "C", "G"];
var C = ["SX", "S", "M", "L", "XL", "XXL", "ML", "LL", "XLL", "MK", "LK", "XLK", "MS", "LS", "XLS"];
var D = ["XLL", "XXL", "XLK"];
function customArrayFunction(A, B) {
var sortB = [];
B.forEach(v => sortB.push(v));
var res = B.sort((a, b) => {
if (a < b)
return -1;
else if (a > b)
return 1;
return 0;
}).find(v => A.indexOf(v) > -1);
return res;
}
document.write(customArrayFunction(A, B));
document.write('<br>' + customArrayFunction(C, D));
提前致谢
最佳答案
这是一个提案,其中为给定数组 ordered
的索引提供了一个临时对象
,并在排序索引小于或大于返回的实际值时进行一些比较.
function x(ordered, search) {
var object = {},
result;
ordered.forEach(function (k, i) {
object[k] = i;
});
search.forEach(function (a) {
if (!result) {
result = [a, a];
return;
}
if (object[a] < object[result[0]]) {
result[0] = a;
return;
}
if (object[a] > object[result[1]]) {
result[1] = a;
}
});
return result;
}
var a = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"],
b = ["B", "J", "A", "C", "G"],
c = ["SX", "S", "M", "L", "XL", "XXL", "ML", "LL", "XLL", "MK", "LK", "XLK", "MS", "LS", "XLS"],
d = ["XLL", "XXL", "XLK"];
document.write('<pre>' + JSON.stringify(x(a, b), 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(x(c, d), 0, 4) + '</pre>');
关于javascript - 使用 JavaScript 编程从另一个数组的值获取数组中最低索引处的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35968262/