Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

how to add, substract, multiplication, divison two arrays in javascript?

  1. User

    how to add, substract, multiplication, divison two arrays in javascript?

  2. Assistant

    To add, subtract, multiply, and divide two arrays in JavaScript, you can use a for loop to iterate over each element in the arrays and perform the desired operation on the corresponding elements.

    For example, to add two arrays:

    // define two arrays
    const arr1 = [1, 2, 3];
    const arr2 = [4, 5, 6];
    
    // create a new array to hold the sum
    const sum = [];
    
    // iterate over each element in the arrays and add them
    for (let i = 0; i < arr1.length; i++) {
      sum.push(arr1[i] + arr2[i]);
    }
    
    console.log(sum); // output: [5, 7, 9]
    

    To subtract two arrays:

    // define two arrays
    const arr1 = [10, 5, 2];
    const arr2 = [3, 2, 1];
    
    // create a new array to hold the difference
    const difference = [];
    
    // iterate over each element in the arrays and subtract them
    for (let i = 0; i < arr1.length; i++) {
      difference.push(arr1[i] - arr2[i]);
    }
    
    console.log(difference); // output: [7, 3, 1]
    

    To multiply two arrays:

    // define two arrays
    const arr1 = [2, 3, 4];
    const arr2 = [5, 6, 7];
    
    // create a new array to hold the product
    const product = [];
    
    // iterate over each element in the arrays and multiply them
    for (let i = 0; i < arr1.length; i++) {
      product.push(arr1[i] * arr2[i]);
    }
    
    console.log(product); // output: [10, 18, 28]
    

    To divide two arrays:

    // define two arrays
    const arr1 = [20, 30, 40];
    const arr2 = [5, 10, 20];
    
    // create a new array to hold the quotient
    const quotient = [];
    
    // iterate over each element in the arrays and divide them
    for (let i = 0; i < arr1.length; i++) {
      quotient.push(arr1[i] / arr2[i]);
    }
    
    console.log(quotient); // output: [4, 3, 2]