算法中如何使用约简?


/*
When consecutive values come into the array, 
delete and count the number
I want to this result
count = 4 // [1, 1, 3, 3]
array = [4, 2, 4]
*/

let count = 0;
let array = [4, 3, 1, 1, 3, 2, 4]

array.reduce((acc, cur) => {
if (acc[acc.length - 1] === cur) {
acc.pop()
count += 2
} 
// this part
else return acc.concat(cur)
}, [])

输入图片描述

我不知道为什么当我在代码中写入'else'字时会出现上述错误和

我想在注释中看到结果。怎么解决才好呢?

您需要分配reduce操作的结果,并返回if块内的累加器,以便下一次迭代:

/*
I want to this result
count = 4 // [1, 1, 3, 3]
array = [4, 2, 4]
*/
let count = 0;
let array = [4, 3, 1, 1, 3, 2, 4]

array = array.reduce((acc, cur) => {
if (acc[acc.length - 1] === cur) {
acc.pop()
count += 2;
return acc;
} else {
return acc.concat(cur);
} 
}, []);
console.log({count, array});

您可以采用稍微不同的方法,只查看值和单个值的收集。

最终的count由两个数组的长度推导而来。

const
array = [4, 3, 1, 1, 3, 2, 4],
result = array.reduce((acc, cur) => {
if (acc[acc.length - 1] === cur) acc.pop();
else acc.push(cur);
return acc;
}, []),
count = array.length - result.length;
console.log(count);
console.log(result);

忘记返回acc

let count = 0;
let array = [4, 3, 1, 1, 3, 2, 4]

let result = array.reduce((acc, cur) => {
if (acc[acc.length - 1] === cur) {
acc.pop()
count += 2
return acc;
} 
else return acc.concat(cur)
}, [])

console.log(count);
console.log(result)

最新更新