skip to Main Content

hi im making this like mini silly program where you have 3 arrays two arrays are filled with four numbers they have to simmilar numbers so i made this for loop to check the similarity between the two arrays and log them into the 3rd array but it prints 2 arrays instead keep in mind am a begiiner my code yea again im a beginner so go easy on me and if you can explaining your code not just the answer and this might trigger you proffesionals sorry if it does 🙂

i tried everrything i tried rewriting the loop i tried modifying it where it pushes j and i but that didnt work

let onArr = [90, 66, 97, 55]
let twoArr = [90, 77, 55, 80]
let threeArr = []

for (let i = 0; i < onArr.length; i++) {
  for (let j = 0; j < twoArr.length; j++) {
    if (onArr[i] === twoArr[j]) {
      threeArr.push(onArr[i])
      console.log(threeArr)
    }
  }
}

2

Answers


  1. The issue is you console.log each time you find a match (of which there are two). You want to log after you find all the matches, so move the log to be after the loops

    let onArr = [90, 66, 97, 55]
    let twoArr = [90, 77, 55, 80]
    let threeArr = []
    
    for (let i = 0; i < onArr.length; i++) {
      for (let j = 0; j < twoArr.length; j++) {
        if (onArr[i] === twoArr[j]) {
          threeArr.push(onArr[i])
        }
      }
    }
    console.log(threeArr)
    Login or Signup to reply.
  2. You could loop through one of the arrays and check if the value is in the other array as well. Checking if a value is in array can be done using the array method includes. If true then add the item to your ‘third array’. Like this:

    let oneArr = [90, 66, 97, 55];
    let twoArr = [90, 77, 55, 80];
    
    function getSame(arr1,arr2) {
      let arr3 = [];
      for (let item of arr1) {
        if (arr2.includes(item)) {
          arr3.push(item);
        }
      }
      return arr3;
    }
    
    console.log(getSame(oneArr, twoArr));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search