1

I have a filter method that filters an item from an array using an if condition. Using the filterArray I then use map method.

I would like to add a second condition and push a new array called OLD_ITEMS to the ITEMS array. How would I go about doing this?

import { OLD_ITEMS, ITEMS } from './constants';

let filterArray = ITEMS.filter(item => {
    if (item.id === 'three') {
        return false;
    }
    return true;
});

// TODO: add second condition here to push `OLD_TIMES` to `ITEMS`  

const options = Object.assign(
    ...filterArray.map(({ id, name }) => ({ [id]: name }))
);
kayee
  • 330
  • 2
  • 6
  • 21

1 Answers1

4

You need to be a little more clear about what you mean by "push" OLD_ITEMS to Items. Do you want to concatenate/push ALL of the OLD_ITEMS to the end of if a single condition is met, or do you want to push subset of OLD_ITEMS that meet a certain condition?

I believe that this is what you're looking for, but it's hard to know exactly:

import { OLD_ITEMS, ITEMS } from './constants';

let filterArray = ITEMS.filter(item => {
    if (item.id === 'three') {
        return false;
    }
    return true;
});

// TODO: add second condition here to push `OLD_TIMES` to `ITEMS`
const validOldItems = OLD_ITEMS.filter(item => {
    if (item === 'some_condition') {
      return false;
    }
    return true;
}

filterArray.push(validOldItems);

const options = Object.assign(
    ...filterArray.map(({ id, name }) => ({ [id]: name }))
);

Also, I highly recommend making your code more concise by returning the value of the conditional check, instead of an if/then

let filterArray = ITEMS.filter(item => {
    return (item.id === 'three');
});

Or even more concise

let filterArray = ITEMS.filter(item => (item.id === 'three'));

Grand finale of conciseness:

const filterArray = ITEMS.filter(item => (item.id === 'three'))
  .concat(OLD_ITEMS.filter(item => (item.id === 'some_condition'))
  .map(({ id, name }) => ({ [id]: name }))

const options = Object.assign(...filterArray);
Aidan Hoolachan
  • 2,285
  • 1
  • 11
  • 14