0

I can't seem to figure out how to filter my array by removing adjacent objects that have the same value of a specified property.

I want to remove adjacent objects with the same item, as the same one would come back eventually later on and I'd still want to have those recorded.

So this array for example...

[
    {
        item: "Car",
        tstamp: 1609605221607
    },
    {
        item: "Car",
        tstamp: 1609605226605
    },
    {
        item: "Truck",
        tstamp: 1609605231610
    },
    {
        item: "Car",
        tstamp: 1609605236604
    }
]

Would filter to this...

[
    {
        item: "Car",
        tstamp: 1609605221607
    },
    {
        item: "Truck",
        tstamp: 1609605231610
    },
    {
        item: "Car",
        tstamp: 1609605236604
    }
]

Removes car's object recorded at 1609605226605

1
  • Show us what you have tried. SO isn't a free code writing service. The objective here is for you to post your attempts to solve your own issue and others help when they don't work as expected. See How to Ask and minimal reproducible example Commented Jan 3, 2021 at 2:26

1 Answer 1

1

You just need a variable to maintain track of what the last item was. Then, you can use the filter method to remove any items that are equal to the lastItem.

const items = [
    {
        item: "Car",
        tstamp: 1609605221607
    },
    {
        item: "Car",
        tstamp: 1609605226605
    },
    {
        item: "Truck",
        tstamp: 1609605231610
    },
    {
        item: "Car",
        tstamp: 1609605236604
    }
];

let lastItem;

const filtered = items.filter(el => {
  if (el.item === lastItem) {
    return false;
  }
  lastItem = el.item;
  return true;
});

console.log(filtered);

Another way to do this would be to use reduce and just compare the current element item to the accumulator's last element. Only add it if they're different.

const items = [
    {
        item: "Car",
        tstamp: 1609605221607
    },
    {
        item: "Car",
        tstamp: 1609605226605
    },
    {
        item: "Truck",
        tstamp: 1609605231610
    },
    {
        item: "Car",
        tstamp: 1609605236604
    }
];

const filtered = items.reduce((acc, el) => {
  const lastItem = acc[acc.length - 1]?.item;
  if (lastItem !== el.item) acc.push(el);
  return acc;
}, []);

console.log(filtered);

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.