Replace in array using lodash

左心房为你撑大大i 提交于 2019-12-10 14:40:41

问题


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.


回答1:


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;
})



回答2:


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'));



回答3:


If the array contains mutable objects, Its a straight forward with lodash find function.

var arr = [{'a':'a'}, {'b':'b'},{'a':'a'},{'c':'c'}];    

while(_.find(arr, {'a':'a'})){
  (_.find(arr, {'a':'a'})).a = 'x';
}

console.log(arr); // [{'a':'x'}, {'b':'b'},{'a':'x'},{'c':'c'}]



回答4:


Another simple solution. Works well with arrays of strings, replaces all the occurrences, reads well.

var arr1 = ['a', 'b', 'a', 'c'];
var arr2 = _.map(arr1, _.partial(_.replace, _, 'a', 'd'));
console.log(arr2); // ["d", "b", "d", "c"]


来源:https://stackoverflow.com/questions/19860039/replace-in-array-using-lodash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!