@dsbasko/filter-by-array v1.0.2
Install
npm i @dsbasko/filter-by-arrayor
yarn add @dsbasko/filter-by-arrayUsage
function filterByArray that takes three arguments:
arr1: an array to filter.
arr2: an array used to filter elements from arr1.
cb: a callback function that takes two arguments: the current element from arr1 and the current element from arr2.
The function returns a new array containing only those elements from arr1 for which the cb function returns true when given the current element from arr1 and at least one element from arr2, or false if given the current element from arr1 and all elements from arr2.
Example
import { filterByArray } from '@dsbasko/filter-by-array';
const persons = [
{ id: 1, name: 'Alice', age: 30 },
{ id: 2, name: 'Bob', age: 25 },
{ id: 3, name: 'Charlie', age: 35 },
];
const idsToFilterBy = [1, 3];
const filteredPersons = filterByArray(persons, idsToFilterBy, (person, id) => person.id === id);
console.log(filteredPersons);
/*
[
{ id: 1, name: 'Alice', age: 30 },
{ id: 3, name: 'Charlie', age: 35 }
]
*/In this example, filterByArray filters the persons array using the idsToFilterBy array as a filter. The callback function compares the value of the id property of each element in the persons array to each element in the idsToFilterBy array. The result of filterByArray is an array of objects containing only those elements from persons whose id matches an element in the idsToFilterBy array. In this case, the result is [{ id: 1, name: 'Alice', age: 30 }, { id: 3, name: 'Charlie', age: 35 }].
Author
Dmitriy Basenko dsbasko.it@gmail.com, GitHub, Twitter, Telegram