is there a function in lodash to replace matched item

前端 未结 15 2323
孤街浪徒
孤街浪徒 2020-12-07 13:42

I wonder if there is a simpler method in lodash to replace an item in a JavaScript collection? (Possible duplicate but I did not understand the answer there:)

I look

15条回答
  •  醉酒成梦
    2020-12-07 14:24

    function findAndReplace(arr, find, replace) {
      let i;
      for(i=0; i < arr.length && arr[i].id != find.id; i++) {}
      i < arr.length ? arr[i] = replace : arr.push(replace);
    }
    

    Now let's test performance for all methods:

    // TC's first approach
    function first(arr, a, b) {
      _.each(arr, function (x, idx) {
        if (x.id === a.id) {
          arr[idx] = b;
          return false;
        }
      });
    }
    
    // solution with merge
    function second(arr, a, b) {
      const match = _.find(arr, a);
      if (match) {
        _.merge(match, b);
      } else {
        arr.push(b);
      }
    }
    
    // most voted solution
    function third(arr, a, b) {
      const match = _.find(arr, a);
      if (match) {
        var index = _.indexOf(arr, _.find(arr, a));
        arr.splice(index, 1, b);
      } else {
        arr.push(b);
      }
    }
    
    // my approach
    function fourth(arr, a, b){
      let l;
      for(l=0; l < arr.length && arr[l].id != a.id; l++) {}
      l < arr.length ? arr[l] = b : arr.push(b);
    }
    
    function test(fn, times, el) {
      const arr = [], size = 250;
      for (let i = 0; i < size; i++) {
        arr[i] = {id: i, name: `name_${i}`, test: "test"};
      }
    
      let start = Date.now();
      _.times(times, () => {
        const id = Math.round(Math.random() * size);
        const a = {id};
        const b = {id, name: `${id}_name`};
        fn(arr, a, b);
      });
      el.innerHTML = Date.now() - start;
    }
    
    test(first, 1e5, document.getElementById("first"));
    test(second, 1e5, document.getElementById("second"));
    test(third, 1e5, document.getElementById("third"));
    test(fourth, 1e5, document.getElementById("fourth"));
    
    
    1. ms [TC's first approach]
    2. ms [solution with merge]
    3. ms [most voted solution]
    4. ms [my approach]

提交回复
热议问题