0

I am struggling a lot with this. I have an array of objects and i want to filter it by key, which means if the array has two object with a certain key i only need to keep the last object.

const mockdata = [
  {
    id: null,
    visibility: 'true',
  },
  {
    id: null,
    visibility: 'true',
  },
  {
    id: null,
    visibility: 'true',
  },
  {
    status: null,
    visibility: 'thid',
  },
];

To look like:

const mockdata = [
  {
    id: null,
    visibility: 'true',
  },
  {
    status: null,
    visibility: 'false',
  },
];
3
  • Duplicated here: javascript and es6 filter array with unique key Commented Jun 23, 2021 at 15:53
  • Why is it status: null, visibility: 'false',? How it it turn to 'false'? Commented Jun 23, 2021 at 16:01
  • It's not clear to me what you want to achieve exactly. What is the key for you, only id and status? Because you seem to ignore visibility. Commented Jun 24, 2021 at 1:54

1 Answer 1

0
let mockdata = [
  {
    id: null,
    visibility: 'true',
  },
  {
    id: null,
    visibility: 'true',
  },
  {
    id: null,
    visibility: 'true',
  },
  {
    status: null,
    visibility: 'thid',
  },
];

mockdata = mockdata.filter((data, index, self) =>
  index === self.findIndex((t) => (
    t.id === data.id && t.visibility === data.visibility && t.status === data.status
  ))
)

While filtering , I am checking for the index using Array.findIndex which returns the index of first item that matches with the condition , so non unique values are not counted

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.