5

Given this typescript code using lodash:

import * as _ from "lodash/fp";

const range = _.range(0, 1000);
let objects = _.uniq(range.map((i) => {
    let foo = "foo";
    let bar = "bar";

    if (i < 5) {
        foo += i.toString(10);
    }

    if (i > 995) {
        bar += i.toString(10);
    }

    return {
        foo,
        bar,
    };
}));

I was expecting to only see the object

{
    "foo": "foo",
    "bar": "bar"
}

once and the total 10 elements with uniq bar and foo strings.

Expected output:

[
    {
        "foo": "foo0",
        "bar": "bar"
    },
    {
        "foo": "foo1",
        "bar": "bar"
    },
    {
        "foo": "foo2",
        "bar": "bar"
    },
    {
        "foo": "foo3",
        "bar": "bar"
    },
    {
        "foo": "foo4",
        "bar": "bar"
    },
    {
        "foo": "foo",
        "bar": "bar"
    },
    {
        "foo": "foo",
        "bar": "bar996"
    },
    {
        "foo": "foo",
        "bar": "bar997"
    },
    {
        "foo": "foo",
        "bar": "bar998"
    },
    {
        "foo": "foo",
        "bar": "bar999"
    }
]

Yet in reality I see all the elements to be kept in the list. It's as if the _.uniq isn't doing anything.

I want to get a unique list of the array based on identity / equalness. All array duplicates for all properties combination shall be removed.

How can I achieve that?

1 Answer 1

5

Note: I'm using lodash/fp. If you use lodash, the order of the args of _.uniqWith are switched.


When you want uniqueness for an object you can use _.uniqWith:

const withoutDupes = _.uniqWith(_.isEqual, objects);
console.log(
    JSON.stringify(withoutDupes, null, 4),
);

As to your first appraoch, keep in mind that _.uniq isn't working on a collection of objects but only works for simple arrays, e.g.:

const simpleArray = [1, 1, 1, 1, 2, 3];
console.log(_.uniq(simpleArray));

outputs:

[ 1, 2, 3 ]
Sign up to request clarification or add additional context in comments.

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.