如何在对象数组中找到要插入的索引。
我有对象数组。
var cordinate = [
[225, 242],
[405, 242],
[585, 242],
[765, 242],
[225, 325],
[405, 325],
[585, 325],
[765, 325],
[225, 408],
[405, 408],
[585, 408],
[765, 408]
]
这里我想插入最近的元素
我要插入的数组
var extraEle = [404, 260]
如何确定坐标中extraEle的确切索引。
这是我正在尝试的
我正在比较 y 坐标以获得最近的范围,然后将 x 坐标与仅 y 范围进行比较以获得索引。
var yValue = [];
var diffVal = cordinate[0][1];
for(var i=0; i<cordinate.length;i++){
if (Math.abs(extraEle[1] - diffVal) > Math.abs(extraEle[1]- cordinate[i][1])){
diffVal = componentsPos[i][1];
}
}
var index;
yvalue = [];
for(var i=0; i<cordinate.length;i++){
if (cordinate[i][1] === diffVal){
yvalue.push(componentsPos[i]);
}
}
var diffValX = yvalue[0][0];
for(var i=0; i<yvalue.length;i++){
if (Math.abs(extraEle[0] - diffValX) > Math.abs(extraEle[0]- yvalue[i][0])){
diffValX = yvalue[i][0];
}
}
var indexValue = [diffValX,diffVal]
cordinate.indexOf(indexValue, 0)
我们可以有比这更好的内置方法吗? 注意:此代码是工作代码。
在我的例子中,输出将是 2,因为 260(Y) 将在前 4 个元素和 404 (X) 的范围内将出现在第三个元素之前。
添加坐标后应该是这样的。
cordinate = [
[225, 242],
[405, 242],
[404, 260],
[585, 242],
[765, 242],
[225, 325],
[405, 325],
[585, 325],
[765, 325],
[225, 408],
[405, 408],
[585, 408],
[765, 408]
]
但准确地说,我只需要可以插入的索引。
最佳答案
这可能不是最优雅的解决方案,但它会确定最近的坐标,通过计算点之间的距离并确定最近的坐标,然后您可以将其拼接
到数组中。
// Input coordinates
let coordinates =
[
[225, 242],
[405, 242],
[585, 242],
[765, 242],
[225, 325],
[405, 325],
[585, 325],
[765, 325],
[225, 408],
[405, 408],
[585, 408],
[765, 408]
];
// Add this to the array
let extraEle = [404, 260];
getClosestIndex(coordinates, extraEle).then((result) => {
coordinates.splice(result, 0, extraEle);
console.log(coordinates);
// Output
/*[
[225, 242],
[405, 242],
[404, 260]
[585, 242],
[765, 242],
[225, 325],
[405, 325],
[585, 325],
[765, 325],
[225, 408],
[405, 408],
[585, 408],
[765, 408]
]; */
});
function getClosestIndex(coords, targetCoords) {
return new Promise((resolve, reject) => {
let shortestDist = 999999999;
let shortestIndex = 0;
coords.forEach((coord, index) => {
let dist = Math.sqrt( Math.pow((coord[0]-targetCoords[0]), 2)
+ Math.pow((coord[1]-targetCoords[1]), 2));
if (dist < shortestDist) {
shortestDist = dist;
shortestIndex = index;
}
});
// To add it after the closest element
if (shortestIndex < coords.length - 1)
shortestIndex += 1;
resolve(shortestIndex);
});
}
关于javascript - 如何找到要插入数组数组的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70358690/