可以說我有兩個陣列如下:
const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr']
const B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa']
我想從陣列 B 中減去陣列 A。結果如下所示:
const result = ['Mo', 'Mo', 'Sa']
如何實作?看起來很簡單,但我無法讓它作業。
本質上,這應該從 B 中洗掉 A 中的所有內容。
uj5u.com熱心網友回復:
const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr']
const B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa']
console.log(A.reduce((b, a)=>
(b.includes(a) && b.splice(b.indexOf(a),1), b), [...B]))
沒有代碼高爾夫:
const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr']
const B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa']
console.log(A.reduce((b, a)=> {
if(b.includes(a)) b.splice(b.indexOf(a), 1); return b; }, [...B]))
uj5u.com熱心網友回復:
filter()A地圖上的一個有趣的小東西。
const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr']
const B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa']
const aMap = A.reduce((a, c) => (a[c] = (a[c] ?? 0) 1, a), {})
const result = B.filter(n => !(aMap[n]-- > 0))
console.log(result)
uj5u.com熱心網友回復:
const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr']
const B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa']
const C = B.map(el => {
const elIndexInA = A.findIndex(e => e === el)
if (elIndexInA === -1) {
return el
}
A.splice(elIndexInA, 1)
}).filter(el => el)
console.log(C)
uj5u.com熱心網友回復:
嘗試這個:
const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr']
const B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa']
let res = B;
A.forEach(val => {
for(let i = 0; i < res.length; i ) {
if(res[i] === val) {
res.splice(res.indexOf(val), 1);
break;
}
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/535356.html
