skip to Main Content

Suppose we have two arrays of different lengths:

let array1 = [22, 42, 28, 100, 28, 48, 38, 48, 26, 32, 58, 36, 28, 42, 42, 38, 28, 28, 38, 24, 32, 38, 38, 28, 46, 38, 42, 46, 32, 46, 38, 48, 9, 6, 5, 8, 5, 56, 24, 32, 5, 46];

let array2 = [25, 50, 75, 100, 150, 250];

It’s necessary multiplication be performed in this way:
22×25, 22×50, 22×75 … 42×25, 42×50 …

How to do this correctly?

4

Answers


  1. You can use Array::reduce() and Array::map() to collect the values:

    let array1 = [22, 42, 28, 100, 28, 48, 38, 48, 26, 32, 58, 36, 28, 42, 42, 38, 28, 28, 38, 24, 32, 38, 38, 28, 46, 38, 42, 46, 32, 46, 38, 48, 9, 6, 5, 8, 5, 56, 24, 32, 5, 46];
    
    let array2 = [25, 50, 75, 100, 150, 250];
    
    
    const result = array1.reduce((r, n) => (r.push(...array2.map(n2 => n * n2)), r), []);
    
    console.log(result);
    Login or Signup to reply.
  2. Here you can do one thing…

    let array1 = [22, 42, 28, 100, 28, 48, 38, 48, 26, 32, 58, 36, 28, 42, 42, 38, 28, 28, 38, 24, 32, 38, 38, 28, 46, 38, 42, 46, 32, 46, 38, 48, 9, 6, 5, 8, 5, 56, 24, 32, 5, 46];
    
    let array2 = [25, 50, 75, 100, 150, 250];
    
    const res = array1.map(a => array2.map(b => a*b))
    
    Login or Signup to reply.
  3. Get ready to dive into the exciting world of JavaScript! We’re going to multiply each element of one array by each element of another, using nested loops. Here’s a handy code snippet to get you started:

    javascript

    let array1 = [22, 42, 28, 100...];
    
    let array2 = [25, 50, 75, 100...];
    
    let resultArray = [];
    
    for (let i = 0; i< array1.length; i++) {
    
    for (let j = 0; j< array2.length; j++) {
    
    resultArray.push(array1[i] * array2[j]);
    
    }
    
    }
    
    console.log(resultArray);
    

    In this thrilling piece of code:

    • We’ve got our arrays array1 and array2 all set up.

    • We create a shiny new empty resultArray where we’ll store our multiplication results.

    • Our nested loops are at work here: the outer loop takes a tour through array1, while the inner loop explores array2.

    • Inside these loops is where the magic happens: we multiply elements from both arrays and push the results into our resultArray.

    • And voila! We log resultArray to reveal all those multiplied values.

    -NAMASTE(0_0)

    Login or Signup to reply.
  4. You could map the products.

    const
        array1 = [22, 42, 28, 100, 28, 48, 38, 48, 26, 32, 58, 36, 28, 42, 42, 38, 28, 28, 38, 24, 32, 38, 38, 28, 46, 38, 42, 46, 32, 46, 38, 48, 9, 6, 5, 8, 5, 56, 24, 32, 5, 46],
        array2 = [25, 50, 75, 100, 150, 250],
        result = array1.map(v => array2.map(w => v * w));
    
    result.forEach(a => console.log(...a));
    .as-console-wrapper { max-height: 100% !important; top: 0; }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search