ramesh
ramesh

Reputation: 1217

Javascript: Find a key with maximum value in a object after filtering keys based on an array

My js object:

data_obj = {'p1': 1, 'p2':2, 'p3':3}

my array

data_array = ['p1', 'p3']

Now, I want to filter the object based on the array. Expected result is

fil_obj = {'p1': 1, 'p3':3}

Now then, find the key having a maximum value. Expected result is

p3

Since I have object with thousands of items, I expect a very efficient solution. Since I'm using d3js for this project, solution based on d3js like d3.max would be great.

Upvotes: 0

Views: 169

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386883

You could iterate the wanted properties and return the max key.

var data_obj = { p1: 1, p2: 2, p3: 3},
    data_array = ['p1', 'p3'],
    result = data_array.reduce(function (r, a, i) {
        return !i || data_obj[r] < data_obj[a] ? a : r;
    }, undefined);

console.log(result);

Upvotes: 2

nnnnnn
nnnnnn

Reputation: 150080

I've never used d3, but it seems to me you can get the result pretty efficiently with a single call to .reduce():

var data_obj = {'p1': 1, 'p2':2, 'p3':3};
var data_array = ['p1', 'p3'];

var results = data_array.reduce((r,v)=>{
  if (v in data_obj) {
    r.data[v] = data_obj[v];
    if (data_obj[v] > r.maxVal) {
      r.maxKey = v;
      r.maxVal = data_obj[v];
    }
  }
  return r;
}, {data:{}, maxKey:null, maxVal:Number.NEGATIVE_INFINITY});

console.log(results);

Upvotes: 1

Related Questions