# JS算法题目4

Lambo
• 313

### 例：

``````let data = [5,6,8,10];
//输入：
let input = [5,8,10,15,18];

let del = []
//输出：
del => [6] //因为input对比data少了6``````

3 个回答
✓ 已被采纳

### 思路一

Lodash 的 `_.difference()` 可以快速实现单向排除

``````import _ from "lodash";

const del = _.difference(data, input);``````

``````function difference(data, refs) {
const set = new Set(refs);
return data.filter(n => !set.has(n));
}``````

### 思路二

`input``data` 排序，用双指针（序号）遍历，挨个查找。

``````let data = [5, 6, 8, 10, 5, 5, 5];
let input = [5, 8, 10, 15, 18, 8, 8, 8];``````

``````{
del: [8, 8, 8, 5, 5, 5, 6]
}``````

``````const diff2 = (prev, cur) => {
const map = new Map();

prev.forEach(n => {
map.set(n, (map.get(n) ?? 0) + 1);
});

cur.forEach(n => {
map.set(n, (map.get(n) ?? 0) - 1);
});

const del = [];
Array.from(map)
.forEach(([k, v]) => {
if (v < 0) { add.push(...make(k, -v)); }
if (v > 0) { del.push(...make(k, v)); }
});

function make(n, times) {
const a = Array(times);
a.fill(n);
return a;
}

};

// { add: [ 8, 8, 8, 15, 18 ], del: [ 5, 5, 5, 6 ] }``````

``const make = (n, times) => ((a) => (a = Array(times).fill(n), a))();``
``````const diff = (prev, cur) => {
const map = {};

for (let i = 0; i < prev.length; ++i) {
if (typeof map[prev[i]] === "undefined") {
map[prev[i]] = 0;
}

++map[prev[i]];
}

const del = [];

for (let i = 0; i < cur.length; ++i) {
if (typeof map[cur[i]] === "undefined") {
continue;
}

if (--map[cur[i]] < 0) {
}
}

for (const key of Object.keys(map)) {
if (map[key] > 0) {
del.push(...Array.from({ length: map[key] }, () => +key));
}
}

};

let data = [5, 6, 8, 10];
//输入：
let input = [5, 8, 10, 15, 18];

console.log(diff(data, input));

``````
``````const data = [5,6,8,10];
//输入：
const input = [5,8,10,15,18];

const del = []

// 先转成set
const dataSet = new Set(data)
// 增加的
for(let item of input){
if(!dataSet.has(item)) del.push(item)
}

console.log(del);

// 先转成set
const inputSet = new Set(input)

// 增加的
for(let item of data){