Kamran Khatti
Kamran Khatti

Reputation: 4127

Filter Object of Array by Index of Other Array

I have a scenario where user can multiselect items and remove them, so I have two arrays:

  1. With checkbox values (checked and index)
  2. The actual items which need to filter based on checked values index.

here are two arrays and expected result using lodash.

const checked = [
  {
    index: 0,
    checked: false
  },
  {
    index: 1,
    checked: true //note second index is checked so we need to filter out second index from items array.
  },
];

const items = [
  {
    title: 'This is title 1',
    description: 'This is description 1',
    end_date: '2018-03-12 14:00:00',
    location: '3577 Rue de Bullion, Montréal, QC H2X 3A1, Canada',
    room: 401,
    start_date: '2018-03-12 13:00:00',
  },
  {
    title: 'This is title 2',
    description: 'This is description 2',
    end_date: '2018-03-12 14:00:00',
    location: '3577 Rue de Bullion, Montréal, QC H2X 3A1, Canada',
    room: 401,
    start_date: '2018-03-12 13:00:00',
  }
];


const result = [
  {
    title: 'This is title 1',
    description: 'This is description 1',
    end_date: '2018-03-12 14:00:00',
    location: '3577 Rue de Bullion, Montréal, QC H2X 3A1, Canada',
    room: 401,
    start_date: '2018-03-12 13:00:00',
  }
];

Upvotes: 0

Views: 32

Answers (2)

Suren Srapyan
Suren Srapyan

Reputation: 68655

You need just to use filter function and get the index of the current object. Then using this index access the n-th item of the checked array (I provide this solution cause from the checked array it is visible that your array contains states for all checkboxes - checked and not checked) and check it's checked property.

const checked = [
  { index: 0, checked: false },
  { index: 1, checked: true }
];

const items = [
  {
    title: 'This is title 1',
    description: 'This is description 1',
    end_date: '2018-03-12 14:00:00',
    location: '3577 Rue de Bullion, Montréal, QC H2X 3A1, Canada',
    room: 401,
    start_date: '2018-03-12 13:00:00',
  },
  {
    title: 'This is title 2',
    description: 'This is description 2',
    end_date: '2018-03-12 14:00:00',
    location: '3577 Rue de Bullion, Montréal, QC H2X 3A1, Canada',
    room: 401,
    start_date: '2018-03-12 13:00:00',
  }
];

const filtered = items.filter((item, index) => !checked[index].checked);

console.log(filtered);

Upvotes: 1

Pawan sasanka
Pawan sasanka

Reputation: 79

You can simply do this.

var result=[];
checked.forEach(function (item) {
    if(item.checked)
    {
        result.push(items[item.index]);
    }
})

console.log(result);

Upvotes: 0

Related Questions