JavaScript Problem: Checking if Two Arrays are Equal

preview_player
Показать описание
We are going to deal with another JavaScript Problem. So the problem is to create a function that will compare two arrays and see if they have the same elements. This problem presents some interesting issues that we will look at.

Would you like to help keep this channel going?

Tutorials referred to in this video:

For more resources on JavaScript:

#javascript #AllThingsJavaScriptLLC
Рекомендации по теме
Комментарии
Автор

function checkArrays(arr1, arr2){

arr1 = arr1.sort((a, b) => a-b);
arr2 = arr2.sort((a, b) => a-b);

return arr1.every((val, idx) => val === arr2[idx]);
}

checkArrays([1, 2, 3], [1, 2, 3])

minnuss
Автор

Thank you, I was so confused why array is a object and I can't do comparing with them.

giant
Автор

Great video. This helped me resolve an issue I was dealing with at work.

mpc
Автор

Great tutorial Steve thank you so much

arunkaiser
Автор

function checkArrays(arr1, arr2)
{
if(arr1.length != arr2.length)
{
console.log(false)
return false
}
for(let i = 0; i < arr1.length; i++)
{
if(arr1[i]!=arr2[i])
{
console.log(false)
return false
}
}
console.log(true)
return true
}
If order matters you can use this code, else... you can just apply a sort and use the above function

SkySentry
Автор

I remember not to long ago you had a tutorial on duplicates in an array. I have to go find that video!

erichrick
Автор

// It's probably been done before, but this my solution.
// I don't need to worry about comparing lengths, because strings are awesome. ^^

const checkArrays = function(array1, array2) {
return array1.sort().toString() === array2.sort().toString();
}
console.log(checkArrays([1, 3, 2, 1], [1, 2, 3, 3]));

cameronbelcher
Автор

If we sort two arrays and then use toString function, it will work in my opinion

Amir-kulp
Автор

Thank you, this was great help :D Subscribed right away!

michellel.
Автор

return [n1, n2, n3].sort(function (a, b) {
return a - b;
});

ilijapavlovic
Автор

Hey Prof. Steven! I liked the idea of having a challenge at the end of the tutorial. Would be nice to have more of those in the future.

So starting where you left off, I came up with a possible solution. It passed a few test cases, including comparing two empty arrays.

'use strict';

const checkArrays = function (arr1, arr2) {

// I kept the length check from your code:

 if (arr1.length !== arr2.length) {
return false;
}

// Then I sorted both arrays:

 arr1.sort();
arr2.sort();

// Lastly I passed the index parameter of 'every' and used it to check the corresponding element on arr2

 return arr1.every((val, i) => val === arr2[i]);
};

Hope this is correct. Thanks again for the great lesson

DesignfulDev
Автор

function checkArraysBySort (arrayOne, arrayTwo) {

// simple length check
if(arrayOne.length !== arrayTwo.length) {
return false;
}

// check if contain all items
if(arrayOne.sort().toString() === arrayTwo.sort().toString() ) {
return true;
}

return false;

}


function checkArraysByRepeatedItems (arrayOne, arrayTwo) {

// simple length check
if(arrayOne.length !== arrayTwo.length) {
return false;
}

// check if contain all items
if(arrayOne.every( (val) => {
return arrayTwo.includes(val);
} )
&&
checkUniqueItems(arrayOne, arrayTwo) ) {
return true;
}

return false;

}

// check if have same number of data
function checkUniqueItems (arrayOne, arrayTwo) {
const dataObject =
{
one: {},
two: {}
};

// create collection based on reapet
for ( let i=0; i< arrayOne.length ; i++) {
let itemOne = arrayOne[i];
let itemTwo = arrayTwo[i];
dataObject['one'][itemOne] = dataObject['one'][itemOne] ? dataObject['one'][itemOne] + 1 : 1;

dataObject['two'][itemTwo] = dataObject['two'][itemTwo] ? dataObject['two'][itemTwo] + 1 : 1;
}
// smaple result
// {
// one: { '1': 1, '2': 1, '3': 2 },
// two: { '1': 1, '2': 1, '3': 2 }
// }


//check same repeat by keys
for ( key of Object.keys(dataObject.one) ) {
if( dataObject.one[key] !== dataObject.two[key]) {
return false
}
}

return true;

}

//checkUniqueItems ([1, 3, 2, 3], [1,2,3,3]);

// solution one
console.log("checkArraysBySort", checkArraysBySort([1, 3, 2, 3], [1,2,3,3]));

// solution two
FALSE", checkArraysByRepeatedItems([1, 3, 2, 1], [1,2,3,3]));

// true sample
TRUE", checkArraysByRepeatedItems([1, 3, 2, 3], [1,2,3,3]));

behrouz-nl
Автор

Thank you! is every() a newer JS function? Have not kept up with ES7 and beyond.

demiansims
Автор

Without the use of .sort() and .toString() or JSON.stringify();
arr1.sort().toString() === arr2.sort().toString();
or
JSON.stringify(arr1.sort()) === JSON.stringify(arr2.sort());
which is simplest way to do it..

let arraysHasSameElements = (arr1, arr2) => {
let count =
// returns counting of occurrences.
(arr, val) => arr.reduce((count, curr) => (curr === val ? 1 : 0) + count, 0);

// if lengths of the arrays is equal, compare them else return false.
return arr1.length === arr2.length

// compare arr1 against arr2.
? arr1.reduce((checks, val) =>

/* creating array of checking if a value has equal amount of occurrences
in both arrays then adds 1 'check'. */
checks.concat( count(arr1, val) === count(arr2, val) ? 1 : 0 ), [])

// checking if every checks is equal to 1, then every returns true.
.every(check => check === 1)

: false;
}

let arr1 = [1, 5, 1, 2, 3, 7, 7],
arr2 = [7, 3, 1, 2, 7, 5, 1];

arraysHasSameElements(arr1, arr2); //true

magnusfohlstrom
Автор

return arr1.toString ===arr2.toString() ;
will not work!
For example:
let arr1 = [1, 2, "abcd", "ef"];
let arr2 = [1, 2, "abcd, ef"];
obviously these arrays are not the same, but if you use "return arr1.toString() === arr2.toString();", it will return true!
because the toString() method on both arrays will convert the arrays into "1, 2, abcd, ef".

weiliyao
Автор

I think we can just get the index value from the every method and compare if the value is equal to the array2[index] which needs to be the same value in the same position

paoloreyes
Автор

Hi Prof. Steven. This is my solution.

const checkArrays = (arr1, arr2) => {
if (arr1.length !== arr2.length) {
return false;
}

return arr1.reduce((store, element, index) => {
if (element !== arr2[index]) {
store = false;
}
return store;
}, true);
};

console.log(checkArrays([1, 3, 2, 1], [1, 2, 3, 3]));

liquidthought
Автор

Thank You so much for this great tutorial, Prof Steve.
could you please make a Video explaining how can we loop into an array ONCE ONLY to compare all the numbers within and return the indexes of the two or more numbers that are the same ?
For example if the array is [7, 1, 3, 4, 1, 7], I want to loop into this array once and get the indexes of the two 7s which is (0 and 5), and the indexes of the two 1s which is (1 and 4).

this was my approach to the problem :
function sameNumbers(a) {
let arr = [];
let res = a.forEach((val, index) =>{
for(let j= index+1; j<a.length; j++){
if(val === a[j]){
arr.push(j, index)
}
}
})
return arr
}

Ismael-jhbx
Автор

This version is stripped of comment and cleaned up....
let arraysHasSameElements = (arr1, arr2) => {
let count = (arr, val) => arr.reduce((count, curr) => (curr === val ? 1:0) + count, 0);
return arr1.length === arr2.length && arr1.reduce((checks, val) =>
checks.concat(count(arr1, val) === count(arr2, val)), []).every(check => check);
}

magnusfohlstrom
Автор

const checkArrays = function ( arr1, arr2 ) {

if ( arr1.length !== arr2.length ) return 0;

// making a copy of arr2
let tmp = arr2.slice();

return arr1.every( val => {

// the value is found within tmp
if ( tmp.includes(val) ) {
// removing the corresponded value from tmp (copy of arr2)
delete tmp[ tmp.indexOf(val) ];
// let every Function to do his/her job
return true;
}

// the value is not presented in tmp!
else return 0;

} );

}

h.tehrani