2023-03-25

 25 Mar 2023

Implement Filter with Reduce

Taken from Execute Program

Use reduce to write a function that behaves like filter. You can do this with only one reduce and no other loops.

filter([1, 2, 3], num => num >= 0) Expected: [1, 2, 3]

filter([1, 2, 3], num => num > 1) Expected: [2, 3]

filter([1, 2, 3], num => num > 5) Expected: []

filter([null, undefined], num => true) Expected: [null, undefined]

filter([], num => true) Expected: []

This is the answer I came up with:

function filter(arr: Array<any>, callback: any) {
  let result: Array<any> = []
  arr.reduce((_, current) => (callback(current)) ? result.push(current) : [], [])
  return result
}

Testing

Solution tested in REPL:

https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABMGAbKBTATgCgIZZYBciAgoXgJ4A8eYlAfADSIR6qoBGeEA1iXUoBKRAG8AsAChEiVBiiIsGAM4h0Jcliq16DRAF5EAbQC6UmQSwA6JQBMQEDDhwB9FhBCEMYKCP16cNg5uPkDPJR8hEQB+RRU1KCsABxBlAAswr0jEElMWUyFzOKhPJCVVdCkAXykpCARlODkrVDgAcxwigHougAEoZQBaGDawOCUilHRsHCMARhYAJhYAZhMWMBAAWwM9TZ29OcLJER7jZcQ1qSA

Copyright © Paramdeo Singh · All Rights Reserved · Built with Jekyll

This node last updated October 9, 2024 and is permanently morphing...

Paramdeo Singh Guyana

Generalist. Edgerunner. Riding the wave of consciousness in this treacherous mortal sea.

Technology Design Strategy Literature Personal Blogs
Search Site

Results are from Blog, Link Dumps, and #99Problems