0

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.

3
  • 2
    "I expect a very efficient solution" - What's your solution? Commented Aug 11, 2016 at 21:26
  • Just write a program to do this. Commented Aug 11, 2016 at 21:30
  • Maybe this answer can halp you? stackoverflow.com/questions/11488194/… Commented Aug 11, 2016 at 21:34

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

1 Comment

I thought the filtered object was also a required output. I guess not. Nice solution for just the key.
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.