How can you remove duplicates from an array of objects using reduce?

  • 0
    How can you remove duplicates from an array of objects using reduce by lastname and get an array of objects without duplicates by lastname?

    const arr = [
      {
         'name': 'anna',
         'lastname': 'petrova'
      },
        {
         'name': 'vika',
         'lastname': 'ivanova'
      },
        {
         'name': 'julia',
         'lastname': 'petrova'
      },
    ]
    JavaScript Scarlett Graham, Sep 26, 2019

  • 3 Answers
  • 0
    Like that?

    const obj = [{
    'name': 'anna',
    'lastname': 'petrova'
    },
    {
    'name': 'vika',
    'lastname': 'ivanova'
    },
    {
    'name': 'julia',
    'lastname': 'petrova'
    },
    ];

    const res = obj.reduce((o, i) => {
    if (!o.find(v => v.lastname == i.lastname)) {
    o.push(i);
    }
    return o;
    }, []);
    console.log(res)
    Harper Harper

  • 0
    // helers start
    const compose = (fn1, fn2) => x => fn1(fn2(x));

    const reduceByProp = prop => a =>
    a.reduce((acc, curr) => ({ ...acc, [curr[prop]]: curr }), {});

    const uniqByProp = prop => compose(Object.values, reduceByProp(prop));
    // helers end

    // logic start
    const uniqByLastname = uniqByProp('lastname')
    const getUniqAndPrint = compose(console.log, uniqByLastname)
    // logic end

    // exec start
    const arr = [
    {
    'name': 'anna',
    'lastname': 'petrova'
    },
    {
    'name': 'vika',
    'lastname': 'ivanova'
    },
    {
    'name': 'julia',
    'lastname': 'petrova'
    },
    ];
    getUniqAndPrint(arr);
    // exec end


    Interactive example
    Anonymous

  • 0
    solution without reduce

    const arr = [{
    'name': 'anna',
    'lastname': 'petrova'
    },
    {
    'name': 'vika',
    'lastname': 'ivanova'
    },
    {
    'name': 'julia',
    'lastname': 'petrova'
    },
    ];
    const table = {};
    const res = arr.filter(({lastname}) =>(!table[lastname] && (table[lastname] = 1)));
    console.log(res)
    Ezra Michael

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!