skip to Main Content

I have an array of objects with a data structure that looks like this:

const fieldArray = [{
    "angle": 32.0,
    "y": 0, 
    "x": 0 
}, { 
    "angle": 33.0,
    "y": 0, 
    "x": 10 
}, { 
    "angle": 34.0, 
    "y": 0, 
    "x": 20 
}, { 
    "angle": 35.0, 
    "y": 0, 
    "x": 30 
}, { 
    "angle": 36.0, 
    "y": 0, 
    "x": 40 
}] //the array I am using is much larger but follows this format

I have a known x and y value. I would like to write a function that finds the object with the matching x and y value and then returns the corresponding angle value. Here’s what I have so far however after writing it I realize I need to use two for loops. Is there an easier way of doing this like using filter or array find for example?

function getFieldAngleValue (x, y) {
    for (let i = 0; i < fieldArray.length; i++){
            if(fieldArray[i].x == x && fieldArray[i].y == y ){
                let index = i
                break
            }
        }
        angle = fieldArray[index].angle;
        return angle;
},

2

Answers


  1. You can use array filter method.
    This is simpled function code.

    function getFieldAngleValue (x, y) {
      filteredArray = fieldArray.filter(a => a.x==x && a.y==y );
      return filteredArray[0].angle;
    }
    
    Login or Signup to reply.
  2. You can achieve this using the Array.find() method, which makes your code more concise and easier to read. The Array.find() method returns the first element in the array that satisfies the provided testing function. If no such element is found, it returns undefined.

    Here’s how you can rewrite your function using Array.find():

    function getFieldAngleValue(x, y) {
        const foundObject = fieldArray.find(obj => obj.x === x && obj.y === y);
        if (foundObject) {
            return foundObject.angle;
        } else {
            return undefined; // or any other value you want to return when no match is found
        }
    }
    

    This code snippet first uses the Array.find() method to search through the fieldArray for an object that matches the provided x and y values. If a matching object is found, it returns the corresponding angle value. If no match is found, it returns undefined, but you can customize the behavior for cases where no match is found.

    This approach eliminates the need for nested loops and improves the readability of your code.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search