Skip to main content

JS Array & Matrix Concepts


JavaScript Array & Matrix Concepts Demo

This demo covers key JavaScript array and matrix operations used in signal processing and general programming.

1. Array Manipulation (1D)


// Original binary array
let inputBits = [0, 1, 1, 0, 1, 0];

// map(): Convert bits to BPSK symbols (0 -> -1, 1 -> 1)
let inputSymbols = inputBits.map(bit => bit===0 ? -1 : 1);
console.log('map():', inputSymbols); // [-1, 1, 1, -1, 1, -1]

// filter(): Split even and odd indices
let s1 = inputSymbols.filter((_, i) => i % 2 === 0); // Even indices
let s2 = inputSymbols.filter((_, i) => i % 2 === 1); // Odd indices
console.log('filter() s1:', s1); // [-1, 1, 1]
console.log('filter() s2:', s2); // [1, -1, -1]

// reduce(): Sum of all bits
let sumBits = inputBits.reduce((sum, b) => sum + b, 0);
console.log('reduce() sum:', sumBits); // 3

// some() / every(): Check conditions
let allValid = inputBits.every(b => b===0 || b===1);
console.log('every() all valid bits?', allValid); // true

2. Pre-allocating Arrays


// Array.from(): Pre-allocate a 2D array for transmitted signals
let numSymbols = inputBits.length;
let transmittedSignals = Array.from({ length: 2 }, () => new Array(numSymbols).fill(0));
console.log('Array.from() 2D array:', transmittedSignals);
/*
[
  [0,0,0,0,0,0],
  [0,0,0,0,0,0]
]
*/

3. Matrix Manipulation (2D)


// Original binary matrix (antennas × time slots)
let bitMatrix = [
  [0, 1, 1],
  [1, 0, 1]
];

// map(): Convert each row to BPSK symbols
let symbolMatrix = bitMatrix.map(row => row.map(bit => bit===0 ? -1 : 1));
console.log('map() 2D matrix:', symbolMatrix);
/*
[
  [-1, 1, 1],
  [1, -1, 1]
]
*/

// flat(): Flatten matrix into 1D array
let flatSymbols = symbolMatrix.flat();
console.log('flat():', flatSymbols); // [-1,1,1,1,-1,1]

// flatMap(): Transform & flatten in one step
let transformedFlat = bitMatrix.flatMap(row => row.map(bit => bit*2));
console.log('flatMap():', transformedFlat); // [0,2,2,2,0,2]

// reduce() per row: sum of each row
let rowSums = bitMatrix.map(row => row.reduce((a,b) => a+b, 0));
console.log('reduce() row sums:', rowSums); // [2,2]

// every() on matrix: check all bits are 0 or 1
let allBitsValid = bitMatrix.every(row => row.every(b => b===0 || b===1));
console.log('every() 2D matrix all valid?', allBitsValid); // true

// Pre-allocate 2D array with Array.from() for matrix
let rows = 2, cols = 3;
let matrixPrealloc = Array.from({ length: rows }, () => new Array(cols).fill(0));
console.log('Array.from() preallocated 2D matrix:', matrixPrealloc);

4. Concepts Summary Table

Concept Similar JS Methods 1D Array Example 2D/Matrix Example
map() → transform each element forEach(), reduce(), flatMap() inputBits.map(bit => bit===0?-1:1) matrix.map(row => row.map(bit => bit===0?-1:1))
filter() → select elements reduce() with condition, some(), every() inputBits.filter((_,i) => i%2===0) matrix.flat().filter((_,i) => i%2===0)
Array.from() → create arrays new Array(length).fill(), spread [...Array(length)], Array.of() Array.from({length:n},()=>0) Array.from({length:rows},()=>new Array(cols).fill(0))
reduce() → combine values array.reduce((acc,val)=>acc+val,0) inputBits.reduce((sum,b)=>sum+b,0) matrix.map(row => row.reduce((a,b)=>a+b,0))
flat() / flatMap() → flatten arrays [].concat(...arrays) [[1,2],[3,4]].flat() → [1,2,3,4] matrix.flatMap(row => row.map(b => b*2))
some() / every() → check conditions logical checks inputBits.every(b => b===0||b===1) matrix.every(row => row.every(b => b===0||b===1))

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Array & Matrix Concepts Demo</title>
<style>
body{
    font-family: Arial, sans-serif;
    background:#f4f6f9;
    margin:40px;
}
.container{
    max-width:700px;
    margin:auto;
    background:white;
    padding:30px;
    border-radius:8px;
    box-shadow:0 3px 12px rgba(0,0,0,0.1);
}
input{
    width:100%;
    padding:12px;
    border:1px solid #ccc;
    border-radius:5px;
    margin-top:10px;
}
.message{
    margin-top:12px;
    font-weight:bold;
}
.valid{ color:#2ecc71; }
.error{ color:#e74c3c; }
pre{
    background:#eee;
    padding:10px;
    border-radius:5px;
    overflow-x:auto;
}
</style>
</head>
<body>

<div class="container" id="container">
    <h1>Array & Matrix Concepts Demo</h1>
    <p>Enter numbers separated by commas (example: <strong>1,2,3,4</strong>)</p>

    <input type="text" id="inputArray" placeholder="Enter numbers here">

    <div id="message" class="message"></div>

    <h2>Results:</h2>
    <pre id="results"></pre>
</div>

<script>
const inputField = document.getElementById("inputArray");
const message = document.getElementById("message");
const results = document.getElementById("results");

// Fixed size for 2D array (rows x cols)
const ROWS = 2;
const COLS = 3;

inputField.addEventListener("input", function() {
    const value = inputField.value.trim();
    if(value === "") {
        message.textContent = "";
        results.textContent = "";
        return;
    }

    // Convert input to numerical array
    let numArray = value.split(',').map(item => Number(item.trim()));

    // Validate input
    if(!numArray.every(n => !isNaN(n))) {
        message.textContent = "Only numbers are allowed.";
        message.className = "message error";
        results.textContent = "";
        return;
    }

    message.textContent = "✓ Valid input!";
    message.className = "message valid";

    // 1. map(): double each element
    let doubled = numArray.map(n => n * 2);

    // 2. filter(): get even numbers
    let evens = numArray.filter(n => n % 2 === 0);

    // 3. reduce(): sum of all numbers
    let sum = numArray.reduce((acc, n) => acc + n, 0);

    // 4. some(): check if any number > 10
    let anyLarge = numArray.some(n => n > 10);

    // 5. every(): check if all numbers >= 0
    let allPositive = numArray.every(n => n >= 0);

    // --- Pad numArray for 2D matrix ---
    let matrixArray = [...numArray];
    let totalSize = ROWS * COLS;
    if(matrixArray.length < totalSize){
        matrixArray = matrixArray.concat(Array(totalSize - matrixArray.length).fill(0)); // pad zeros
    } else if(matrixArray.length > totalSize){
        matrixArray = matrixArray.slice(0, totalSize); // truncate
    }

    // 6. Array.from(): create 2D matrix
    let matrix = Array.from({ length: ROWS }, (_, r) =>
        matrixArray.slice(r * COLS, r * COLS + COLS)
    );

    // --- Pad for flatMap ---
    let flatMapArray = [...numArray];
    if(flatMapArray.length < totalSize){
        flatMapArray = flatMapArray.concat(Array(totalSize - flatMapArray.length).fill(0));
    }
    let flatMapped = flatMapArray.flatMap(n => [n, n]);

    // --- Pad for flat() ---
    let flatMatrix = matrix.flat();

    // Display results
    results.textContent = `
Original array: [${numArray}]
map() - doubled: [${doubled}]
filter() - even numbers: [${evens}]
reduce() - sum: ${sum}
some() - any number > 10? ${anyLarge}
every() - all numbers >= 0? ${allPositive}
Array.from() - 2D matrix (padded to ${ROWS}x${COLS}): ${JSON.stringify(matrix)}
flatMap() - duplicate each element (padded if needed): [${flatMapped}]
flat() - flattened matrix: [${flatMatrix}]
    `;
});
</script>

</body>
</html>


Output 

 

Contact Us

Name

Email *

Message *

Popular Posts

UGC NET Electronic Science Previous Year Question Papers with Solutions

Home / Engineering & Other Exams / UGC NET 2026 PYQ ⬇️ Download Papers and Solutions 📋 Exam Pattern 💡 Preparation Tips ❓ FAQs 📊 Exam Highlights: Electronic Science (88) Feature Details Junior Research Fellowship (JRF) ₹37,000 + HRA per month Eligibility M.Sc/M.Tech in Electronics (55%) Validity of Certificate JRF (3 Years) | Lectureship (Lifetime) 📥 Download UGC NET Electronics PDFs Complete collection of previous year question papers, answer keys and explanations for Subject Code 88. Start Downloading 📂 View All Question Papers June 2025 - Question Paper Download PDF June 2025 - Solved Paper + Explanation ...

UGC NET Electronic Science June 2025 Question Paper with Answer Key & Detailed Solutions

Home / UGC NET PYQ / June 2025 Solved UGC NET Electronic Science June 2025 Question Paper with Answer Key and Full Explanations 📥 Download Question Paper (PDF) 2025 2024 2023 2022 2021 2020 Explanations 1.  Answer: Option (3) For forming a p-type semiconductor, the dopant must be a trivalent impurity (three valence electrons) so that it creates acceptor levels and holes become the majority carriers. Among the given elements, boron (B) is a group-III element (trivalent). Arsenic (As) and phosphorus (P) are group-V (pentavalent) donors that produce n-type material, and germanium (Ge) is a group-IV element usually used as the semiconductor, not as an acceptor dopant. Hence, doping an intrinsic semiconductor with B produces a p-type semiconductor. 2.  Answer: Option (4) The ohmic resistance of a JFET at zero gate bias is given by the standard relation: R DS(on) = V P / I DSS ...

BER vs SNR for M-ary QAM, M-ary PSK, QPSK, BPSK, ...(MATLAB Code + Simulator)

Bit Error Rate (BER) & SNR Guide Analyze communication system performance with our interactive simulators and MATLAB tools. 📘 Theory 🧮 Simulators 💻 MATLAB Code 📚 Resources BER Definition SNR Formula BER Calculator MATLAB Comparison 📂 Explore M-ary QAM, PSK, and QPSK Topics ▼ 🧮 Constellation Simulator: M-ary QAM 🧮 Constellation Simulator: M-ary PSK 🧮 BER calculation for ASK, FSK, and PSK 🧮 Approaches to BER vs SNR What is Bit Error Rate (BER)? The BER indicates how many corrupted bits are received compared to the total number of bits sent. It is the primary figure of merit f...

Online Simulator for ASK, FSK, and PSK

Interactive Digital Signal Processing (DSP) Tutorial and Simulator for ASK, FSK, and BPSK modulation techniques. Try our new Digital Signal Processing Simulator!   •   Interactive ASK, FSK, and BPSK tools updated for 2025. Start Now Digital Modulation Visualizer: ASK, FSK, & BPSK Simulator Learn and visualize binary modulation techniques (ASK, FSK, BPSK) in real-time with adjustable carrier and sampling parameters. Perfect for DSP students and engineers. 📡 ASK Simulator 📶 FSK Simulator 🎚️ BPSK Simulator 📚 More Topics ASK Modulator FSK Modulator BPSK Modulator More Topics 1. ASK (Amplitude Shift Keying) Simulat...

Constellation Diagrams of ASK, PSK, and FSK (with MATLAB Code + Simulator)

Constellation Diagrams: ASK, FSK, and PSK Comprehensive guide to signal space representation, including interactive simulators and MATLAB implementations. 📘 Overview 🧮 Simulator ⚖️ Theory Q-function 📚 Resources 📂 Other Topics: M-ary PSK & QAM Diagrams ▼ 🧮 Simulator for M-ary PSK Constellation 🧮 Simulator for M-ary QAM Constellation BASK (Binary ASK) Modulation Transmits one of two signals: 0 or -√Eb, where Eb​ is the energy per bit. These signals represent binary 0 and 1. BFSK (Binary FSK) Modulation Transmits one of two signals: +√Eb​ (On the y-axis, the phas...

Theoretical BER vs SNR for binary ASK, FSK, and PSK (with MATLAB Code + Simulator)

📘 Overview & Theory 🧮 MATLAB Codes 🧮 Q-function 📚 Further Reading Bit Error Rate (BER) Equations In ASK, noise directly affects the signal amplitude, making it the most vulnerable since the data is carried in amplitude changes. In FSK, data is represented by frequency variations, and because noise typically impacts amplitude more than frequency, FSK is more robust than ASK. In PSK, data is encoded in the signal phase, and BPSK specifically uses 180-degree phase shifts, creating the greatest separation between signal points and therefore achieving the lowest bit error rate (BER) for the same power level. BER formulas for ASK, FSK, and PSK modulation schemes. ASK BER = 0.5 × erfc(0.5 × √SNR) FSK BER = 0.5 × erfc(√(SNR / 2)) PSK BER = 0.5 × erfc(√SNR) ...

UGC NET Electronic Science December 2024 Question Paper with Answer Key & Detailed Solutions

Home / UGC NET PYQ / June 2025 Solved UGC NET Electronic Science December 2024 Question Paper with Answer Key and Full Explanations 📥 Download Question Paper (PDF) 2025 2024 2023 2022 2021 2020 Q.1 Answer: Option (3) Q.2 Answer: Option (3) Solution 1. JMP SHORT LABEL Intrasegment (within the same code segment). Direct jump. ❌ Not intersegment indirect. 2. JMP 5000H:2000H Intersegment (far jump because both CS and IP are specified). Direct jump (address is explicitly given). ❌ Not indirect. 3. JMP [2000H] The destination address is taken from memory location 2000H. This is indirect. In 8086, a far indirect jump can use a memory operand containing both IP and CS (depending on operand size), making it an intersegment indirect jump. ✅ Correct answer. 4. JMP [BX] Indirect jump through memory addressed by BX. Usually intrasegment (near indirect jump). ❌ Not in...

MATLAB Code for ASK, FSK, and PSK (with Online Simulator)

MATLAB Code for ASK, FSK, and PSK Comprehensive implementation of digital modulation and demodulation techniques with simulation results. 📘 Theory 📡 ASK Code 📶 FSK Code 🎚️ PSK Code 🕹️ Simulator 📚 Further Reading Amplitude Shift Frequency Shift Phase Shift Live Simulator ASK, FSK & PSK HomePage MATLAB Code MATLAB Code for ASK Modulation and Demodulation COPY % The code is written by SalimWireless.Com clc; clear all; close all; % Parameters Tb = 1; fc = 10; N_bits = 10; Fs = 100 * fc; Ts = 1/Fs; samples_per_bit = Fs * Tb; rng(10); binar...