我有一个数组,有时有重复的元素顺序地互相跟随。例如:
["<app-builder-navbar></app-builder-navbar>",
"<app-builder-placeholder></app-builder-placeholder>",
"<app-builder-hero></app-builder-hero>",
"<app-builder-placeholder></app-builder-placeholder>",
"<app-builder-placeholder></app-builder-placeholder>",
"<app-builder-footer></app-builder-footer>"]
我想删除所有重复元素(即<app-builder-placeholder></app-builder-placeholder>
)依次相继的实例。所以上面的结果看起来像这样:
["<app-builder-navbar></app-builder-navbar>",
"<app-builder-placeholder></app-builder-placeholder>",
"<app-builder-hero></app-builder-hero>",
"<app-builder-placeholder></app-builder-placeholder>",
"<app-builder-footer></app-builder-footer>"]
我下面的方法似乎有些奏效,但<app-builder-placeholder></app-builder-placeholder>
有时会删除所有项目或产生不稳定的结果集。
function deleteDuplicatePlaceholders(components) {
for (let i = 0; i < components.length; i++) {
for (let j = 1; j < components.length; j++) {
if (components[i] === '<app-builder-placeholder></app-builder-placeholder>' &&
components[j] === '<app-builder-placeholder></app-builder-placeholder>') {
components.splice(i, 1);
}
}
}
}
我怎样才能解决这个问题?
可以很干净地完成此操作Array#filter
。想法是将当前元素与其先前的元素进行比较,如果匹配则将其从结果中忽略。对于a
包含的边缘情况要格外小心undefined
(添加a.slice(1)
会有所帮助)。
const dedupeAdjacent = a => a.filter((e, i) => e !== a[i-1]);
const placeholders = [
"<app-builder-navbar></app-builder-navbar>",
"<app-builder-placeholder></app-builder-placeholder>",
"<app-builder-hero></app-builder-hero>",
"<app-builder-placeholder></app-builder-placeholder>",
"<app-builder-placeholder></app-builder-placeholder>",
"<app-builder-footer></app-builder-footer>"
];
console.log(dedupeAdjacent(placeholders));
如果您需要将重复数据删除行为限制为一个元素(或一组元素),则将其作为参数传递以使该函数可重复使用。
const dedupeAdjacent = (a, target) =>
a.filter((e, i) => e !== a[i-1] || e !== target)
;
const placeholders = [1, 1, 1, 2, 2, 3, 4, 1, 1, 3, 3];
console.log(dedupeAdjacent(placeholders, 1));
最后,这里是针对一系列目标元素的。如果您期望targets
输入大量或大量,请构建一个Set
,否则仅用于includes
避免堆分配。您也可以将集合缓存在调用方中并传递给它,但这有点麻烦。
const dedupeAdjacent = (a, targets) =>
a.filter((e, i) => e !== a[i-1] || !targets.includes(e))
;
const dedupeAdjacentWithLotsOfTargets = (a, targets) => {
targets = new Set(targets); // this step is expensive
return a.filter((e, i) => e !== a[i-1] || !targets.has(e));
};
const placeholders = [1, 1, 1, 2, 2, 3, 4, 1, 1, 3, 3];
console.log(dedupeAdjacent(placeholders, [1, 3]));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句