Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace in array using lodash

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.

like image 826
Andreas Köberle Avatar asked Nov 08 '13 13:11

Andreas Köberle


2 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;
})
like image 155
Benjamin Gruenbaum Avatar answered Sep 19 '22 12:09

Benjamin Gruenbaum


I don't know about "simpler", but you can make it reusable

function swap(ref, replacement, input) {
    return (ref === input) ? replacement : input;
}

var a = ['a', 'b', 'a', 'c'];

_.map(a, _.partial(swap, 'a', 'x'));
like image 43
Tomalak Avatar answered Sep 19 '22 12:09

Tomalak