Get all items from a list using javascript filter method

Viewed 146

I want to filter items from the list. When a certain category will be provided as a value to the target variable, the filter method should return only items with that category. but when no category is provided I want to get items of all categories regardless of category. In my code below works ok, but I want more clear logic to filter items when no category is provided as a target.

let items = [
  {'name':"A",'category':"a"},
  {'name':"B",'category':"b"},
  {'name':"C",'category':"c"}
]
let target;
console.log(items.filter( item => {
    if(target==undefined){
    return true;
  }
    return (item['category']===target);
}));
3 Answers

You can create a function that takes a list of items and an optional target. In case a target was passed return the filtered list, otherwise, return the list itself:

const filterByCategoryIfTargetProvided = (arr = [], target) =>
  target ? arr.filter(({ category }) => category === target) : arr;

const items = [ {'name':"A",'category':"a"}, {'name':"B",'category':"b"}, {'name':"C",'category':"c"} ];

console.log( filterByCategoryIfTargetProvided(items) );
console.log( filterByCategoryIfTargetProvided(items, 'a') );

You coiuld filter by either no category or with the category.

const
    filter = (data, category) => data.filter(o => !category || o.category === category),
    items = [{ name: "A", category: "a" }, { name: "B", category: "b" }, { name: "C", category: "c" }];

console.log(filter(items));
console.log(filter(items, 'a'));
.as-console-wrapper { max-height: 100% !important; top: 0; }

This function requires an array and the object you want to filter. You can use it to filter the object based on the category, name or any other object key. Thanks.

let items = [
{ name: "A", category: "a" },
{ name: "B", category: "b" },
{ name: "C", category: "c" },
];

const filterItems = (arr, itemToFilter) => {
if (itemToFilter) {
    const keyToFilter = Object.keys(itemToFilter);
    const filteredItem = arr.filter((eachItem) => {
        return eachItem[keyToFilter] === itemToFilter[keyToFilter];
    });
    return filteredItem;
} else {
    return arr;
}
};

console.log(filterItems(items, { category: "a" }));

Related