Ready to test code:
Array.from of arr1 = const ( new new the Array (100000), (Item, index) => { return index; }); const arr2 is = Array.from ( new new the Array (50000), (Item, index) => { return index 2 * ; }); the console.log ( 'start test' ); const start = new new a Date () the getTime ();. DISTINCT (of arr1, arr2 is); // method to weight const End = new new a Date () .getTime ( ); the console.log ( 'end of the test' ); the console.log ( 'test time' + (end - start) / 1000 + 's');
一:filter + indexOf
function distinct(arr1, arr2) { console.log('filter + indexOf'); const arr = [...arr1, ...arr2]; return arr.filter((item, index) => { return arr.indexOf(item) === index; }); }
Effect: Time 11s
II: double loop, delete (splice) duplicates
function distinct(a, b) {
the console.log ( 'double loop for');
ARR const = a.concat (B); for (I = 0 the let, len = arr.length; I <len; I ++ ) { for (J = I + the let. 1; J <len; J ++ ) { IF (ARR [ I] == ARR [j]) { arr.splice (j, . 1 ); // splice will change the length of the array, so to the length of the array index j and len minus one len-- ; j - ; } } } return ARR }
Effect: 22s
三、includes + push
function distinct(arr1, arr2) { console.log('includes + push新数组'); const arr = [...arr1, ...arr2]; const result = []; for (item of arr) { !result.includes(item) && result.push(item); } return result; }
Effect: 11s
Fourth, the first sort (sort), then compare the two approaching
function distinct(arr1, arr2) { console.log('先排序, 比较临近的2个 然后push'); let arr = [...arr1, ...arr2]; arr = arr.sort((a, b) => {return a - b}); const result = []; for (let i = 0, len = arr.length; i < len; i++) { (arr[i] !== arr[i + 1]) && result.push(arr[i]); } return result; }
Effect: 0.03s
Fourth, use set
function distinct(arr1, arr2) { console.log('使用set'); const arr = [...arr1, ...arr2]; return Array.from(new Set(arr)); }
Effect: 0.04s
Five, for recycling with the use of the object, and then push
function distinct(arr1, arr2) { console.log('for循环配合对象使用,然后push'); const arr = [...arr1, ...arr2]; const len = arr.length; const obj = {}; const result = []; for (let i = 0; i < len; i++){ if (!obj[i]) { result.push(arr[i]); obj[i] = 1; } } return result; }
Effect: 0.03s
六、reduce
function distinct(arr1, arr2) { console.log('reduce'); const arr = [...arr1, ...arr2]; arr.reduce((prev, cur) => { if (!prev.includes(cur)) { return [...prev, cur]; } else { return prev; } }, []); }
Effect: 110s