Is there an easy way to replace all appearances of an primitive in an array with another one. So that ['a', 'b', 'a', 'c'] would become ['x', 'b', 'x', 'c'] when replacing a with x. I'm aware that this can be done with a map function, but I wonder if have overlooked a simpler way.
5 Answers
In the specific case of strings your example has, you can do it natively with:
myArr.join(",").replace(/a/g,"x").split(",");
Where "," is some string that doesn't appear in the array.
That said, I don't see the issue with a _.map - it sounds like the better approach since this is in fact what you're doing. You're mapping the array to itself with the value replaced.
_.map(myArr,function(el){
return (el==='a') ? 'x' : el;
})
3 Comments
Andreas Köberle
The question was about primitives not just strings. Also I want to use lodash, as this will be one step in a longer chain, where the array data is manipulated in.
Benjamin Gruenbaum
@AndreasKöberle First of all using a particular library is a mean and not a goal. Second of all - in that case
_.map is what you're looking for, underscore/lodash has no specific replace/swap functionality on collections, you can add it to the lodash prototype yourself if you'd like.Denys Séguret
_.map is really fit to this use case, there's no need to look for anything else.
A replace method like this one could work:
const replacer = (contextArray, itemToReplace, replaceWith) => _.map(
contextArray,
(n) => n === itemToReplace ? replaceWith : n
)
console.log(replacer(['a', 'b', 'a', 'c'], "a", "x"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.19/lodash.min.js"></script>
map()in this case? It's the perfect tool for the job._(array).filter('someKey').replace('a', 'x')looks very natural to me