-2

I have an array of objects like this:

[{"name" : "Annie", "number" : 25},
{"name" : "Zeus", "number" : 25},
{"name" : "John", "number" : 40},
{"name" : "John", "number" : 32},
{"name" : "Zeus", "number" : 75},
{"name" : "Zeus", "number" : 32} ]

I would like to filter this such that I have one instance of each unique name and that instance must give me the largest number less than or equal to 40. The above case, if filtered, would return:

[{"name" : "Annie", "number" : 25},
{"name" : "John", "number" : 40},
{"name" : "Zeus", "number" : 32} ]

The final array does not have to be sorted in any particular order.

3
  • 1
    You should add the code you've tried. Commented May 9, 2016 at 1:24
  • 1
    Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example. Commented May 9, 2016 at 1:25
  • You should probably loop over the array with filter and create an index object of the names encountered. Keep the first of each with a value <= 40 and if duplicates are found, keep the one with the highest value <= 40. What have you tried? Commented May 9, 2016 at 1:26

1 Answer 1

0

It's a pretty simple challenge with an O(N) solution. A function do so so would be this:

function solution(A)
{
    var endObj = {};
    for (var i=0, ii=A.length; i<ii; i++)
    {
        var val = A[i];

        if (val.number > 40)
            continue;

        if (!endObj[val.name]) {
            endObj[val.name] = val;
            continue;
        }

        if (endObj[val.name].number < val.number)
            endObj[val.name] = val;
    }

    var endArr = [];
    for (var key in endObj)
        endArr.push(endObj[key]);

    return endArr;
}

I just tracked the names by using them as the key to a new object, then convert that object to a keyless Array once finished.

JSfiddle example here: https://jsfiddle.net/qa7vzvp5/

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

1 Comment

Thanks, this really helps and works great for my case.

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.