redrom
redrom

Reputation: 11642

How to get index of the array item with nearest value?

I have following array of the objects in json and i would like to get index of the object in array which is nearest by count of days attribute opposite the given number value.

Exist any built-in function in jQuery or JS for this, or how can i easily solve it please?

Thanks for any help.

"warningAttributes": [
                        {
                            "id": "3",
                            "days": 15,                          
                            "color": "#FFFFFF"                 
                        },
                        {
                            "id": "4",
                            "days": 98,                          
                            "color": "#343434"                  
                        }
                    ]

Upvotes: 1

Views: 1272

Answers (6)

Andy
Andy

Reputation: 63550

Chris has pretty much stolen this (+1), but here's a breakdown of how I attempted it:

function getDays(arr, value) {

    // get a list of the differences between the requested value
    // and the numbers in the array and make them all positive
    var abs = arr.map(function (el) { return Math.abs(el.days - value); });

    // find the smallest number
    var smallest = Math.min.apply(null, abs);

    // find out where that number is in the positive number array
    var index = abs.indexOf(smallest);

    // return an object that contains the index of the
    // object, and the number of days that were closest
    return { index: index, value: arr[index].days };
}

var result = getDays(arr, 35); // Object { index: 3, value: 17 }

Get the index with result.index.

DEMO

Upvotes: 0

Sevanteri
Sevanteri

Reputation: 4048

Here's my go because writing short code is fun.

var warningAttributes =  [{"id": "3", "days": 15, "color": "#FFFFFF"},
                          {"id": "4", "days": 98, "color": "#343434"}]

var n = 90; 
var distances = warningAttributes.map(function(c) {return Math.abs(n - c.days);})
var nearest_idx = distances.indexOf(Math.min.apply(Math, distances));

Upvotes: 0

Manjar
Manjar

Reputation: 3268

As easy as this:

function getNearest(arr,value)
{
  var diff = null;
  var index= 0;
  $.each(arr,function(i,item) {
    var current = Math.abs(item.days - value);
    if (diff == null) diff = current;
    if (current< diff) 
       index=i;
  });
  return index
}

Upvotes: 0

Chris Charles
Chris Charles

Reputation: 4446

var warningAttributes =  [{"id": "3", "days": 15, "color": "#FFFFFF"},
                          {"id": "4", "days": 98, "color": "#343434"}]

var target = 90; 

var nearest = warningAttributes.sort(function(a,b){ 
    return Math.abs(a.days-target) - Math.abs(b.days-target)
})[0];

This also gives you the list of the nearest, if you leave off [0]

Upvotes: 7

Carlo G.
Carlo G.

Reputation: 152

If I uderstand well:

    jQuery(document).ready(function () {
    var control=40;
    var json = {"warningAttributes": [
                        {
                            "id": "3",
                            "days": 15,                          
                            "color": "#FFFFFF"                 
                        },
                        {
                            "id": "4",
                            "days": 98,                          
                            "color": "#343434"                  
                        },
                         {
                            "id": "5",
                            "days": 40,                          
                            "color": "#343434"                  
                        }
                    ]};
   $.each(json.warningAttributes, function(k, v) {
       var diff;
       diff= control - v.days
       if(diff==0) alert("this is your element: " + v.id);
   })
});

Upvotes: 0

Naeem Shaikh
Naeem Shaikh

Reputation: 15715

Considering you are trying to find the ID which is closest.

you can do this, http://jsfiddle.net/s4jq5kv7/ . though you will need to clean the code, but this works.

var id=3;
var temp;
var prev;

var x={"warningAttributes": [
                        {
                            "id": "3",
                            "days": 15,                          
                            "color": "#FFFFFF"                 
                        },
                        {
                            "id": "4",
                            "days": 98,                          
                            "color": "#343434"                  
                        }
                    ]
      }
prev=x.warningAttributes[0].id;
val=prev;
$(x.warningAttributes).each(function(i,ele){

    if(id>parseInt(ele.id)){
        temp=id-parseInt(ele.id);
    }else{
                temp=parseInt(ele.id)-id;
    }
    if(prev>temp)
    {prev=temp;
     val=ele.id;}
})

console.log(val)

The only problem would be, if there is a number which has same difference with more than two numbers, in that case the first one is returned. Ex 3 and 4, and if you find nearest to 3.5, you get the first number i.e 3.

Upvotes: 0

Related Questions