ภาพรวม
บทความนี้สาธิตวิธีรวมอาร์เรย์ 2 มิติของ Boolean ด้วย AND Operator (&&) ตามคอลัมน์
ตัวอย่าง
Input: [[true, false, false], [false, false, false], [false, false, true]]
Column 0: true && false && false = false
Column 1: false && false && false = false
Column 2: false && false && true = false
Output: [false, false, false]
การนำไปใช้
const andMerge = (arr = []) => {
return arr.reduce((acc, val) => {
val.forEach((bool, ind) => {
acc[ind] = (acc[ind] ?? true) && bool;
});
return acc;
}, []);
};
console.log(andMerge([[true,false,false],[false,false,false],[false,false,true]]));
ผลลัพธ์
[false, false, false]
วิธีการทันสมัย
// Transpose + Every
const andMergeModern = (matrix) => {
const cols = Math.max(...matrix.map(r => r.length));
return Array.from({ length: cols }, (_, i) =>
matrix.every(row => row[i] === true)
);
};
// Zip + Map
const zip = (...arrays) =>
Array.from({ length: Math.max(...arrays.map(a => a.length)) }, (_, i) =>
arrays.map(a => a[i])
);
const andMergeZip = (matrix) =>
zip(...matrix).map(col => col.every(Boolean));
Boolean Algebra Properties
- Identity: a && true = a
- Annihilator: a && false = false
- Idempotent: a && a = a
- Commutative: a && b = b && a
- Associative: (a && b) && c = a && (b && c)
การประยุกต์ใช้
- Feature Flags: ทุก Environment ต้อง Enable
- Permission Systems: User ต้องมี Permission ทั้งหมด
- Circuit Design: AND Gate Simulation
- Data Validation: ทุก Rule ต้อง Pass
- Query Optimization: Predicate Pushdown
ข้อควรระวัง
- Jagged Arrays: คอลัมน์สั้นกว่า -> ค่า Default (true สำหรับ AND)
- Non-boolean Values: JavaScript Truthy/Falsy Conversion
- Short-circuit: reduce ไม่ Short-circuit ได้ ต้องใช้ Loop
Short-circuit Version
const andMergeShortCircuit = (matrix) => {
if (matrix.length === 0) return [];
const cols = Math.max(...matrix.map(r => r.length));
const result = new Array(cols).fill(true);
for (const row of matrix) {
for (let i = 0; i < cols; i++) {
if (result[i] && row[i] === false) {
result[i] = false;
}
}
}
return result;
};