我有2个阵列偶尔会改变一次。我想比较它们并获得添加和放大第一个,源数组和第二个数组之间的删除。
添加/删除可能发生在数组的中间(不一定在边缘)。
例如,从这些数组:
Array 1
Item A | Item B | Item C | Item D | Item E
Array 2
Item A | Item Z | Item C | Item D | Item E
我想获得以下输出: - 项目B已被删除 - 项目Z已添加
处理这个问题的最佳方法是什么?
答案 0 :(得分:5)
如果项目类型是字符串,请按照
进行操作var getAddedorRemovedItem = function (sourceArray1, sourceArray2) {
var added = [], removed = [];
sourceArray1.forEach(function(item){
if (sourceArray2.indexOf(item) == -1) {
removed.push(item);
}
});
sourceArray2.forEach(function (item) {
if (sourceArray1.indexOf(item) == -1) {
added.push(item);
}
});
// here added array contain all new added item and removed contain all removed item;
// do acc. to whatever you want to get outpur
}
答案 1 :(得分:0)
这可以在线性时间内完成。
当我们有唯一的数组时(更简单的算法)
const getDifferenceUnique = (arrayA, arrayB) => {
const valuesByFrequencies = (accumulator, value) => ({
...accumulator,
[value]: true,
});
const dictionaryA = arrayA.reduce(valuesByFrequencies, {});
const dictionaryB = arrayB.reduce(valuesByFrequencies, {});
return {
// get only those values from the `arrayA` that AREN'T present in the
// `arrayB`. This will get us an array containing the REMOVED items only.
deletions: arrayA.filter((value) => !dictionaryB[value]),
// get only those values from the `arrayB` that AREN'T present in the
// `arrayA`. This will get us an array containing the ADDED items only.
additions: arrayB.filter((value) => !dictionaryA[value])
}
};
const { deletions, additions } = getDifferenceUnique(['1', '2'], ['2', '3']);
console.log('Deletions', deletions);
console.log('Additions', additions);
当我们有非唯一数组时
const getDifference = (arrayA, arrayB) => {
const valuesByFrequencies = (accumulator, value) => ({
...accumulator,
[value]: accumulator[value] ? accumulator[value] + 1 : 1
});
const dictionaryA = arrayA.reduce(valuesByFrequencies, {});
const dictionaryB = arrayB.reduce(valuesByFrequencies, {});
const createMapValuesByFrequencies = (dictionary) => ([key, frequency]) => {
const difference = (dictionary[key] || 0) - frequency;
return difference < 0 ? [key, difference] : null;
}
const filterNulls = (value) => value;
const getValuesByFrequencies = (accumulator, [key, frequency]) => [
...accumulator,
...key.repeat(Math.abs(frequency)).split('')
];
return {
deletions: Object.entries(dictionaryA)
.map(createMapValuesByFrequencies(dictionaryB))
.filter(filterNulls)
.reduce(getValuesByFrequencies, []),
additions: Object.entries(dictionaryB)
.map(createMapValuesByFrequencies(dictionaryA))
.filter(filterNulls)
.reduce(getValuesByFrequencies, [])
};
};
const { deletions, additions } = getDifference(['1', '2', '2', '2', '2'], ['2', '3', '3']);
console.log('Deletions', deletions);
console.log('Additions', additions);
答案 2 :(得分:-1)
如果元素具有随机位置,那么唯一认为你可以做的就是遍历数组以确定添加或删除哪些元素,或者你也可以使用underscore lib它有一个节点包
功能是:
_.difference(array, *others)
此致