How to find the index to be insterted in array of object.
I have array of Object.
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]
]
Here i want to nearest element to be inserted
array which i want to insert
var extraEle = [404, 260]
How to detremine the exact index for the extraEle in cordinate.
Here is what I am trying
I am comparing y cordinate to get the nearest range and then comparing x cordinate with only y range to get index.
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)
Can we have something inbuilt or better approach than this. Note : This code is working code.
The output in my case will be 2 because 260(Y) will be in range of first 4 element and 404 (X) will come before third element.
After adding my cordinate should be like.
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]
]
But precisely I need only index where I can insert.