I created a array with objects in javascript. that's what i got:
object[
{position:1, value:23},
{position:34, value:22 },
{position:2, value:10},
{position:35,value:9}.....
]
So i want to create a for loop, that deletes those objects who's destination (eg destination =(object1.position - object2.position) *-1) is lower than 18 to the previous objects.
for example: object[2].position is 1 position apart from object[0].position so object[2] is not needed anymore. The same for object[3] ... 35 - 34 = 1 / 1<18 / object[3] not needed.
that's what i wrote:
myfullarray = [
{pos:1,value:23},
{pos:34,value:22},
{pos:2,value:10},
(...)
]
myarray = [];
myarray[0] = {
pos:myfullarray[0].pos,
value:myfullarray[0].value
}
for(i=1;i<myarray.length;i++){
for(d=i;d>0;d--){
mydest = myfullarray[i].pos-myfullarray[d].pos;
if(mydest<0){
mydest *= -1
}
if(mydest<18){
}else{
myarray[myarray.length + 1] = {
value:myfullarray[i].value,
pos:myfullarray[i].pos
};
}
}
}
Can someone help me with this problem ?
Here's a suggestion that avoids iterating quadratically. Create a new array. Then iterate through your full array, keeping track of the minimum and maximum positions so far, and if the current object has a position that's less than 18 from the minimum and maximum, add it to the new array.
EDIT: Here's a quick write-up of the code.
myFullArray = ...
myArray = [];
myArray[0] = myFullArray[0];
var min = myArray[0].pos;
var max = myArray[0].pos;
var current;
for (i = 1; i < myFullArray.length; i++) {
current = myFullArray[i].pos;
if (Math.abs(current - min) < 18) && Math.abs(current - max) < 18)
{
myArray.push(myFullArray[i]);
if (current < min)
min = current;
else if (current > max)
max = current;
}
}
This should do the tick if you wanted to stick closer to your original algorithm.
myfullarray = [
{position:1, value:23},
{position:34, value:22 },
{position:2, value:10},
{position:35,value:9}
]
myarray = [];
myarray[0] = {
pos:myfullarray[0].position,
value:myfullarray[0].value
}
myfullarray.splice(0,1);
var mindest = 18;
for(i=0;i<myarray.length;i++){
var myobject = myarray[i];
for(d=i;d<myfullarray.length;d++){
mydest = myobject.position-myfullarray[d].position;
if(mydest<0){
mydest *= -1
}
if(mydest<mindest){
myfullarray.splice(d, 1);
}
}
if (i < myfullarray.length) {
myarray.push(myfullarray[i]);
myfullarray.splice(i,1);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.