1

I have an array offers with objects that look like so:

{ 
    sellItem: {
        id: _, 
        quantity: _
    }, 
    buyItem: {
        id: _, 
        quantity: _
    }, 
    volume: _
}

I would like to find duplicates - meaning offers with the same 'sell id' and 'buy id'. I would also like to log the index of these items in the original "offers" array.

I tried doing this for 2 days but did not manage to get anywhere because I found it too difficult to write what I'd like to do in a manageable amount of lines. The other questions on StackOverflow were concerned with only one object rather than with nested objects.

Example of what my offers array looks like:

{sellItem: {id: Pizza, quantity: 2}, buyItem: {id: Dollar, quantity: 1}, volume: 1}
{sellItem: {id: Pizza, quantity: 3}, buyItem: {id: Dollar, quantity: 2}, volume: 1}
{sellItem: {id: Banana, quantity: 2}, buyItem: {id: Pound, quantity: 1}, volume: 1}
{sellItem: {id: Apple, quantity: 2}, buyItem: {id: Euro, quantity: 1}, volume: 1}
{sellItem: {id: Pizza, quantity: 5}, buyItem: {id: Dollar, quantity: 3}, volume: 1}

And the expected result here:

0: Selling 2x Pizza for 1x Dollar
1: Selling 3x Pizza for 2x Dollar
4: Selling 5x Pizza for 3x Dollar

All other entries from the "offers" array should be ignored because they are not duplicate offers.

1 Answer 1

1

You can use filter along with find to search for another element with the same id.

const arr = [{sellItem: {id: 'Pizza', quantity: 2}, buyItem: {id: 'Dollar', quantity: 1}, volume: 1},
{sellItem: {id: 'Pizza', quantity: 3}, buyItem: {id: 'Dollar', quantity: 2}, volume: 1},
{sellItem: {id: 'Banana', quantity: 2}, buyItem: {id: 'Pound', quantity: 1}, volume: 1},
{sellItem: {id: 'Apple', quantity: 2}, buyItem: {id: 'Euro', quantity: 1}, volume: 1},
{sellItem: {id: 'Pizza', quantity: 5}, buyItem: {id: 'Dollar', quantity: 3}, volume: 1}];
const res = arr.filter(({sellItem: {id}},idx)=>
   arr.find(({sellItem:{id:id2}},idx2) => idx !== idx2 && id === id2));
console.log(res);

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

2 Comments

Wow! It took you only a few dozen seconds to come up with something that took me 2 days of ripping my hair out. Thanks so much! I will study this code to find out exactly how it works.
@vxern Happy to help.

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.