问题
I have browsed over the Lodash docs quite a bit and can't seem to find what I'm looking for.
I want to know if Lodash has a method or simple combo of methods to remove all remaining elements in an array once a certain match has been detected, including the match itself.
For example:
let blogArray = ["check", "out", "my", "blog", "https", "someblog", "com"]
let matchingEl = "https"
_.doAThing(blogArray, matchingEl)
=> ["check", "out", "my", "blog"]
回答1:
This can be achieved using indexOf and splice functions of an Array object. Below are the implementation using both Lodash and javascript functions
blogArray.splice(0,blogArray.indexOf(matchingEl))
_.slice(blogArray, 0, _.findIndex(blogArray, function(k){return k == matchingEl;})
回答2:
This is endearing to me
_.doAThing(blogArray)
Because it so boldly embodies a technique of programming called wishful thinking – it captures this idea that your program is as elegant as you want it to be; make a magic wand, wave it on some arguments, and your program works! And it does, we just have to write _.doAThing...
We can easily traverse an array using recursion. To design a recursive function, we have a base case, and inductive cases
- base case –
itemsis empty, return an empty array - inductive case 1 –
itemsis not empty, therefore we have at least one element – if thefirstitem matches'https', we're done and there are no elements to follow; return empty array. - inductive case 2 – the
firstitem does not match, concat thefirstitem with the recursive result of therestof the items.
const doAThing = (items = []) =>
isEmpty (items)
? []
: first (items) === 'https'
? []
: [ first (items) ] .concat (doAThing (rest (items)))
Ok, so this is exactly how I would like to express doAThing – the idea is I just keep wishing functions along the way. Now I just need to write isEmpty, first, and rest
const isEmpty = (items = []) =>
items.length === 0
const first = (items = []) =>
items [0]
const rest = (items = []) =>
items.slice (1)
And allakhazam! Like magic, your program is done. Note, we can collapse the first two cases using || because each case returns the same []
const doAThing = (items = []) =>
isEmpty (items) || first (items) === 'https'
? []
: [ first (items) ] .concat (doAThing (rest (items)))
const isEmpty = (items = []) =>
items.length === 0
const first = (items = []) =>
items [0]
const rest = (items = []) =>
items.slice (1)
const data =
["check", "out", "my", "blog", "https", "someblog", "com"]
console.log (doAThing (data))
// [ 'check', 'out', 'my', 'blog' ]
An obvious improvement would be to make the https match a parameter of the function
const doAThing = (match, items = []) =>
isEmpty (items) || first (items) === match
? []
: [ first (items) ] .concat (doAThing (match, rest (items)))
console.log (doAThing ('https', data))
// [ 'check', 'out', 'my', 'blog' ]
来源:https://stackoverflow.com/questions/48921597/lodash-method-for-removing-all-elements-in-array-after-match-found