Home > OS >  How to check if the the difference of and number and a value from my object in my array is smaller t
How to check if the the difference of and number and a value from my object in my array is smaller t

Time:06-13

I need to access an object and it's property and check if the the value of the property smaller than 100 is.

My code would look like following:

    let myArr = [{
    id: 1,
    x: 120,
    y: 150,
    }, {
    id: 2,
    x: 170,
    y: 420,
    }, {
    id: 3,
    x: 160,
    y: 220,
    }, {
    id: 4,
    x: 140,
    y: 170,

}];
    if(nearestEnemy.x - /*go throught all of my "x"-properties*/ && nearestEnemy.y - /*go throught all of my "y"-properties*/ < 100){
    
    }

You don't need to matter about the other code, just look at my comments.
I want to check if the x axis and the y axis is almost the same as of one of my properties from my object in my array.
I guess you'd need something like a loop for this but I can't think of anything!
I don't know if you can understand me because I cant really explain what I mean.

Thanks for you help anyway.

CodePudding user response:

You can achieve this by filtering out the objects by using Array.filter() method.

let myArr = [{
  id: 1,
  x: 120,
  y: 150
}, {
  id: 2,
  x: 170,
  y: 420
}, {
  id: 3,
  x: 160,
  y: 220
}, {
  id: 4,
  x: 140,
  y: 170
}];

function difference(a, b) {
  return Math.abs(a - b);
}

const filtered = myArr.filter(({x, y}) => difference(x, y) < 100);

console.log(filtered);

CodePudding user response:

It sounds to me like you have an array of points and want to find an element which is the nearest to the given point. If this is the case, you can proceed like this:

Example:

let myArr = [
    {
        id: 1,
        x: 120,
        y: 150,
    }, {
        id: 2,
        x: 170,
        y: 420,
    }, {
        id: 3,
        x: 160,
        y: 220,
    }, {
        id: 4,
        x: 140,
        y: 170,

    }];


function distance(p1, p2) {
    return Math.sqrt(
        (p1.x - p2.x) ** 2   (p1.y - p2.y) ** 2,
    )
}


function nearestPoint(points, somePoint) {
    let min =  Infinity,
        minPt = null;

    for (let p of points) {
        let d = distance(p, somePoint);
        if (d < min) {
            min = d;
            minPt = p;
        }
    }

    return minPt;
}


console.log(nearestPoint(myArr, {x: 190, y: 130}))

This is not very efficient, but should be fine for < 10,000 points. If you have more, you'll need some kind of spatial indexing.

  • Related