Removing elements with Array.map in JavaScript

后端 未结 8 2064
无人及你
无人及你 2020-12-08 12:43

I would like to filter an array of items by using the map() function. Here is a code snippet:

var filteredItems = items.map(function(item)
{
            


        
8条回答
  •  执念已碎
    2020-12-08 13:07

    I just wrote array intersection that correctly handles also duplicates

    https://gist.github.com/gkucmierz/8ee04544fa842411f7553ef66ac2fcf0

    // array intersection that correctly handles also duplicates
    
    const intersection = (a1, a2) => {
      const cnt = new Map();
      a2.map(el => cnt[el] = el in cnt ? cnt[el] + 1 : 1);
      return a1.filter(el => el in cnt && 0 < cnt[el]--);
    };
    
    const l = console.log;
    l(intersection('1234'.split``, '3456'.split``)); // [ '3', '4' ]
    l(intersection('12344'.split``, '3456'.split``)); // [ '3', '4' ]
    l(intersection('1234'.split``, '33456'.split``)); // [ '3', '4' ]
    l(intersection('12334'.split``, '33456'.split``)); // [ '3', '3', '4' ]

提交回复
热议问题