Answer the question
In order to leave comments, you need to log in
How to sort objects by distance, knowing the coordinates in JS?
There is a definition of the current location of the user. You need to make a filter to display objects by distance, starting from the closest to the farthest. To do this, as I understand it, you need to display them in ascending order of distance from smaller to larger. How to find out these distances if the coordinates of each object are known (they will be, say, in the data attributes of the objects) in JS?
Answer the question
In order to leave comments, you need to log in
Geometry. Some kind of class
1. In fact, we have a bunch of vectors.
2. They all start at one point (current). For convenience, keep it as (0, 0)
3. The coordinates of your points are the ends of the vectors
4. Calculate the length of each vector
//тут массив с вашими объектами
var items = [ {x: 1, y: 1},
{ x: 22, y: 0},
{ x: 2, y: 0},
{ x: 0, y: 1},
{ x: 2, y: 2},
{ x: 1, y: 2},
]
//тут будут храниться пары {объект, удаленность}
var sorteditems = [];
//получаем для каждого удаленность
items.forEach(getLength);
//сортируем по удаленности. сначала самые ближние. Если поставить {return b.len - a.len;}, то будут сначала самые дальние
var res = sorteditems.sort(function compare(a, b){return a.len - b.len;});
//фсе
console.log(res);
//вот тут описано, как получаем для каждого удаленность
function getLength(item, index, array) {
var len = Math.sqrt(Math.pow(item.x, 2) + Math.pow(item.y, 2));
sorteditems.push({item, len});
}
var point_1 = {
x: 10,
y: 20
};
var point_2 = {
x: 17,
y: 3
};
var vector = {
x: point_1.x - point_2.x,
y: point_1.y - point_2.y
};
var vecror_length = Math.sqrt(vector.x * vector.x + vector.y * vector.y);
var distance = vector_length;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question