intersection

Simplest code for array intersection in javascript

亡梦爱人 提交于 2019-11-25 21:38:34
问题 What\'s the simplest, library-free code for implementing array intersections in javascript? I want to write intersection([1,2,3], [2,3,4,5]) and get [2, 3] 回答1: Use a combination of Array.prototype.filter and Array.prototype.indexOf: array1.filter(value => -1 !== array2.indexOf(value)) Or as vrugtehagel suggested in the comments, you can use the more recent Array.prototype.includes for even simpler code: array1.filter(value => array2.includes(value)) For older browsers: array1.filter(function

Removing duplicates in lists

家住魔仙堡 提交于 2019-11-25 21:38:14
问题 Pretty much I need to write a program to check if a list has any duplicates and if it does it removes them and returns a new list with the items that weren\'t duplicated/removed. This is what I have but to be honest I do not know what to do. def remove_duplicates(): t = [\'a\', \'b\', \'c\', \'d\'] t2 = [\'a\', \'c\', \'d\'] for t in t2: t.append(t.remove()) return t 回答1: The common approach to get a unique collection of items is to use a set. Sets are unordered collections of distinct