Search code examples
javascriptarraysobjectlodash

How can get the closes object from object array?


I'm trying to get the closest object from object array. if there is not matched element, I'd like to get the most closest one from array? Here are the examples: for example, let's assume that the array is as following:

const array = [
  { element1: 50, element2: 100, element3: 200, element4: 90 },
  { element1: 150, element2: 110, element3: 200, element4: 190 },
  { element1: 250, element2: 120, element3: 190, element4: 290 },
  { element1: 350, element2: 130, element3: 120, element4: 390 },
  { element1: 450, element2: 140, element3: 140, element4: 490 },
  { element1: 550, element2: 150, element3: 160, element4: 590 },
]

and I set the value on settings as following: { element1: 60, element2: 100, element3: 200, element4: 100 },,

Then actually, there is no element matched with this one on the array. and at that time, it returns the most closest one from them. in that case, the first element would be returned - { element1: 50, element2: 100, element3: 200, element4: 90 }.


Solution

  • You can make use of reduce then sorting the values based on the output:

    var array = [ { element1: 50, element2: 100, element3: 200, element4: 90 }, { element1: 150, element2: 110, element3: 200, element4: 190 }, { element1: 250, element2: 120, element3: 190, element4: 290 }, { element1: 350, element2: 130, element3: 120, element4: 390 }, { element1: 450, element2: 140, element3: 140, element4: 490 }, { element1: 550, element2: 150, element3: 160, element4: 590 }];
    
    var settings = { element1: 60, element2: 100, element3: 200, element4: 100 };
    
    var [difference, result] = Object.entries(array.reduce((acc, elem)=>{
      difference = 0;
      Object.keys(elem).forEach(k=>difference+=Math.abs(elem[k]-settings[k]));
      acc[difference] = acc[difference] || [];
      acc[difference].push(elem);
      return acc;
    },{})).sort((a,b)=>a[1]-b[1])[0];
    
    console.log(result);
    console.log(difference)