Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,708 questions

55,472 answers

573 users

How to find the N smallest values in a 2D list in JavaScript

1 Answer

0 votes
/*
    Find the N smallest values in a 2D array.

    Approach:
    1. Flatten the 2D array into a single list.
    2. Sort the list.
    3. Take the first N values.

    JavaScript's built‑in array methods make this approach expressive
    and efficient for typical workloads.
*/

// Flatten a 2D array into a single list
function flatten(matrix) {
    // matrix.flat() works because the array is only 2 levels deep
    return matrix.flat();
}

// Extract the N smallest values
function smallestN(matrix, n) {
    const flat = flatten(matrix);

    // Sort ascending
    const sorted = flat.slice().sort((a, b) => a - b);

    // Return the first N values
    return sorted.slice(0, n);
}

// Main

const matrix = [
    [42, 12, 85,  3],
    [ 7, 99, 15, 23],
    [64,  1, 18, 30],
    [ 3, 55, 11, 90]
];

const n = 5;

const values = smallestN(matrix, n);

console.log(`The ${n} smallest values:`);
console.log(values.join(" "));


/*
run:

The 5 smallest values:
1 3 3 7 11

*/

 



answered 4 days ago by avibootz
...