0

I have 2 arrays, one is the items list and second one is a selected items list:

const orig = [
  {
    id: "1",
    name: "First",
    price: "100",
    qty: "1",
    sum: 1
  },
  {
    id: "2",
    name: "Second",
    price: "100",
    qty: "1",
    sum: 1
  },
  {
    id: "3",
    name: "Third",
    price: "99",
    qty: "1",
    sum: 1
  }
];

const selected = [
  {
    id: "1",
    name: "First",
    price: "100",
    qty: "1",
    sum: 1
  }
  // {
  //   id: "2",
  //   name: "Second",
  //   price: "100",
  //   qty: "1",
  //   sum: 1
  // }
];

I can loop over 2 arrays at the same time:


const arr = [];

orig.forEach((o) => {
  selected.forEach((s) => {
    if (o.id !== s.id) {
      arr.push(o);
    }
  });
});

console.log(arr);

It works fine, when selected array has only 1 item, but if selected array got at least 2 items (second item is commented) then it doesn't work. Main purpose of this code is to remove selected items from orig array.

2
  • Specifically orig.filter(o => !selected.find(s => s.id === o.id)) Commented Apr 19, 2022 at 16:51
  • @evolutionxbox it did, thanks Commented Apr 19, 2022 at 16:53

2 Answers 2

0

We can do this in two lines of code

const selectedIds = selected.map(({id}) => id)

This stores all the id values of objects from the selected array. Based on the example given, selectedIds will have the value [ "1" ].

Then,

const arr = orig.filter(object => !selectedIds.includes(object.id))

This remvoes any object from orig that has an id that is in the selectedIds array.

Full Solution:

const selectedIds = selected.map(({id}) => id)
const arr = orig.filter(object => !selectedIds.includes(object.id))
Sign up to request clarification or add additional context in comments.

Comments

0

You can do this in a single line.

const orig = [
    {
        id: '1',
        name: 'First',
        price: '100',
        qty: '1',
        sum: 1,
    },
    {
        id: '2',
        name: 'Second',
        price: '100',
        qty: '1',
        sum: 1,
    },
    {
        id: '3',
        name: 'Third',
        price: '99',
        qty: '1',
        sum: 1,
    },
    {
        id: '4',
        name: 'Fourth',
        price: '69',
        qty: '420',
        sum: '9001',
    },
];

const selected = [
    {
        id: '1',
        name: 'First',
        price: '100',
        qty: '1',
        sum: 1,
    },
    {
        id: '2',
        name: 'Second',
        price: '100',
        qty: '1',
        sum: 1,
    },
];

const removeSelected = (arr, selected) => {
    return arr.filter(({ id }) => !selected.some((obj) => obj.id === id));
};

console.log(removeSelected(orig, selected));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.