[javascript] How to compare arrays in JavaScript?

I think the simplest way is to turn each array into a string like you tried, and compare the strings.

To convert the arrays into string, just put this string of methods onto the arrays. These are the arrays:

var arr1 = [1, 2, "foo", 3, "bar", 3.14]
var arr2 = [1, 2, "foo", 3, "bar", 3.14]

Now, you have to convert them into the strings. The list of methods are:

arr1.toString().replace(/,/gi, "")
arr2.toString().replace(/,/gi, "")

The methods do:

**.toString()** -

Turns array into a string, concatenating the elements of the array.

Ex. ["tree", "black hole"] -> "tree,black hole"

Sadly, it includes the commas. That is why we have to do:

***.replace(a, b)***

It finds and replaces the first argument (a) with the second argument (b) in the string you are doing it on.

Ex.

"0000010000010000000".replace("1", "2")

will return: "0000020000010000000"

It only replaces the first instance of parameter 1, so we can do regex instead.

Ex.

"0000010000010000000".replace(/1/gi, "2")

will return: "0000020000020000000"

You wrap what you want to replace with /. Say what you want to replace is 1. You make it: /1/. But then you have to add the gi at the end so that it selects every instance. So, you have to put /1/gi with a comma at the end, and then you can put what you want to replace it with.

Now, your two arrays are:

arr1: "12foo3bar3.14" arr2: "12foo3bar3.14"

Now you say this:

if(arr1 === arr2) {
  // Now the code you put inside of this if statement will only run if arr1 and arr2 have the same contents.
} else {
  // This code will run if arr1 and arr2 have any differences.
}

If you want to check if arr1 CONTAINS arr2 instead of having the same exact contents, you do this.

if(arr1.indexOf(arr2) !== -1) {
    //This code will happen if arr2 is inside of arr1. If there is one extra array 
    //item in arr1, it doesn't matter. But, if arr2 has an extra array item, nothing in 
    //this if will run. If you want arr2 to contain arr1, just make arr1 in the 
    //condition of this if arr2, and make arr2 arr1.
}

Basically, if you want the arrays to be the EXACT SAME, do this:

if(arr1.toString().replace(/,/gi, "") === arr2.toString().replace(/,/gi, "")) {
    //arrays are the same
} else {
    //arrays are different
}

And if you want to know if an array contains another, just do this:

arrayThatWillHoldAnotherArray = arrayThatWillHoldAnotherArray.toString().replace(/,/gi)
arrayThatWillBeInsideAnotherArray = arrayThatWillBeInsideAnotherArray.toString().replace(/,/gi)


if(arrayThatWillHoldAnotherArray.indexOf(arrayThatWillBeInsideAnotherArray) !== -1) {
    //arrayThatWillHoldAnotherArray has arrayThatWillBeInsideAnotherArray inside of it
} else {
    //it doesn't
}

_x000D_
_x000D_
console.log("Read the code to understand this.")
var arr1 = [1,2,"foo",3,"bar",3.14]
var arr2 = [1,2,"foo",3,"bar",3.14]
function checkIfArraysAreTheSame(a,b) {
  if(a.toString().replace(/,/gi,"") === b.toString().replace(/,/gi,"")) {
    console.log("A and B are the same!")
    return true;
  }
  console.log("A and B are NOT the same!")
  return false
}
checkIfArraysAreTheSame(arr1,arr2)
//expected output: A and B are the same!
//Now, let's add another item to arr2.
arr2.push("Lorem")
checkIfArraysAreTheSame(arr1,arr2)
//expected output: A and B are NOT the same!

function checkIfArrayIsNestedInsideAnother(a,b) {
  //If this returns true, b is nested inside a.
  if (a.toString().replace(/,/gi,"").indexOf(b.toString().replace(/,/gi,"")) > -1) {
    console.log("B is nested inside of A!")
  } else if(b.toString().replace(/,/gi,"").indexOf(a.toString().replace(/,/gi,"")) > -1) {
    console.log("A is nested inside of B!")
  }
}

checkIfArrayIsNestedInsideAnother(arr1, arr2)
//expected output: A is nested inside of B! because:
//arr1 (a): [1,2,"foo",3,"bar",3.14]
//arr2 (b): [1,2,"foo",3,"bar",3.14, "Lorem"]
//We added Lorem at line 15.

//Now, let's check if arr2 is nested inside arr1, which it is not.
checkIfArrayIsNestedInsideAnother(arr2, arr1)
//expected output: B is nested inside of A!
_x000D_
_x000D_
_x000D_

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?