Hello brilliant minds, Welcome again in a new episode of series called JavaScript useful snippets. In this series, I'm going to talk about some short-codes and useful functions of JavaScript. These snippets can help you to make your development more efficient and faster. Stay tuned till the end to learn something new... π
JavaScript useful snippet - bifurcate()
Guess you have an array with tons of records from them you need some records which are truthy or match with any other rule you've given in one dataset, while rest records in another dataset at those times this function can make it happen in few secs. bifurcate() will take two arguments as input, first one will be an array of records and the second one will be rule in the type of function.
After, processing in the output it'll return two arrays inside array where first will consist records which satisfy with your rules and second will have rest records. Let's look at the syntax for better understanding...
const bifurcateBy = (arr, fn) =>
arr.reduce((acc, val) => (acc[fn(val) ? 0 : 1].push(val), acc), [[], []]);
In return, I've used reduce method to differencing arrays, while as the initial value I've passed [[], []] into it. and in return of reduce(), I've first selected the index of output array by validating given function (means if current records satisfy the given rule then index will be 0 otherwise 1) and did push the record into a selected array. So, that's how both arrays will be treated here. now, let's check out results...
Result:
const result = bifurcateBy(['Jan', 'May', 'April', 'Sep'], x => x[1] === 'a'); // output [ ["Jan", "May"], ["April", "Sep"]]
As you see in a result - Given arrays bifurcated into two arrays where the first one includes who satisfy condition which added in the second argument and second result array includes all records who are not matched with the condition.
Thank you for watching/reading folks, if you found this informative and wanted to make me more content like this please support me on Patreon.
Now, Guys in the next episode I'm going to share a function to get a distance between two points in the 2D dimension. so follow/subscribe to get notification...
Subscribe on youtube https://www.youtube.com/channel/UCvNjso_gPQIPacA6EraoZmg
Facebook: https://www.facebook.com/KatharotiyaRajnish/
Twitter: https://twitter.com/tutorial_spot
Top comments (0)