-1

How can I solve this problem?

..An array of integers is given. Check if it contains the same elements. Maybe my idea is right, but I don't know how I can do this. One more thing. I can use Loops, but without ForEach, function, and something similar. Thank you.

let array = [2, 4, 3, 0, 1];
let array2 = [2, 4, 3, 0, 1];

for (let b = 0; b < array2.length; b ++) {
  for (let i = 1; i < array.length; i ++) {
    if (array2[b] == array[i]) {
      console.log('there are');
    } else {
    }
  }
}
Derek Wang
  • 10,098
  • 4
  • 18
  • 39

3 Answers3

1

This should work for you, I changed your arrays to be input as parameters to the a reusable function.

function compareArrays(array1, array2) {
   if(array1.length != array2.length) {
       return false
    }
   for (i = 0; i < array1.length; i++) {
      if(!hasInArray(array2, array[i])) {
          return false
      }
   }
   return true
 }

function hasInArray(array, item) {
   let foundIt = false
   for(j = 0; j < array.length; j++) {
       if(array[j] == item) {
          foundIt = true
       }
   }
   return foundIt
 }
Nathan Walsh
  • 358
  • 2
  • 4
  • `[1, 1, 2]` and `[2, 2, 1]` <= your logic would return true, yes? – Taplar Oct 09 '20 at 21:21
  • Yes, but those two arrays do contain the same elements. I guess you can interpret " contains the same elements" in a lot of ways. Like did he mean contains the same number of the same elements? If so then my solution would need a little adjustment. – Nathan Walsh Oct 09 '20 at 21:34
  • Right, this question is not clear at all towards what the user wants. – Taplar Oct 09 '20 at 21:35
0

if need to compare two arrays with primitive types by unique values:

let array1 = [4, 5, 6, 1, 3];
let array2 = [5, 5, 3, 4, 6, 1];

const reprUniqArray = arr => Array.from(new Set( arr )).sort().toString();

let result = reprUniqArray(array1) == reprUniqArray(array2)

Dmytro Ivashchenko
  • 195
  • 1
  • 3
  • 9
0

let ra = [2, 4, 3, 0, 1];
let hasDuplicates = false;
let i = 0;
while (i < ra.length) {
  let k = i + 1;
  while (k < ra.length && !hasDuplicates) {
    ra[i] === ra[k] ? hasDuplicates = true : k++;
  }
  i = hasDuplicates ? ra.length : i + 1;
}
console.log(hasDuplicates);
pank
  • 132
  • 1
  • 3