0

i have an empty array and need to append array through a nested for loop.

const arr1=[ [ 1,3 ], [ 5,4 ], [ 8,6, 11 ], [ 15, 19, 12 ] ];
const arr2=[ [21,23],[ 3, 2 ], [ 1,4 ], [  5, 6 ,11 ] ];

const arr3=[];
console.log('Lost assests counts');


for (let i=0;i<arr1.length;++i)
{

    const arrTemp=[]
    arrTemp.push(arr1[i].length)
    
    for (let j=i+1;j<arr2.length;++j){
        
        const intersection = arr2[j].filter(element => arr1[i].includes(element));

        arrTemp.push(intersection.length)
        
        
    }
    console.log(arrTemp);

}

This returns the below output(this is the output of arrTemp inside the loop):

enter image description here

Instead of the above output, Can I have it like the below way?

[[2,1,1,0],[2,1,1],[3,2],[3]]
2
  • Printing? You should convert the array to a string to control what it looks like as output.
    – James
    Commented Sep 15, 2022 at 12:11
  • define arrTemp outside of loops as let arrTemp = [] then put console.log(JSON.stringify(arrTemp)); outside of loops as well.
    – zer00ne
    Commented Sep 15, 2022 at 12:15

1 Answer 1

3

Did you just want to push the values to arr3? In that case, instead of printing the value within the loop:

console.log(arrTemp);

Push it to the target array in the loop:

arr3.push(arrTemp);

Then after the loop, print the whole thing:

console.log(arr3);

Full example:

const arr1=[ [ 1,3 ], [ 5,4 ], [ 8,6, 11 ], [ 15, 19, 12 ] ];
const arr2=[ [21,23],[ 3, 2 ], [ 1,4 ], [  5, 6 ,11 ] ];

const arr3=[];
console.log('Lost assests counts');


for (let i=0;i<arr1.length;++i)
{

    const arrTemp=[]
    arrTemp.push(arr1[i].length)
    
    for (let j=i+1;j<arr2.length;++j){
        
        const intersection = arr2[j].filter(element => arr1[i].includes(element));

        arrTemp.push(intersection.length)
        
        
    }
    arr3.push(arrTemp); // I changed this

}

console.log(arr3); // I added this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.