Compare two arrays in javascript - javascript

I'd like to check which elements are equal in my two arrays, but can't get it working.
This is my code:
for (var i; i < bombs.length; i++) {
for (var j; j < bombsDb.length; j++) {
if (bombs[i].name === bombsDb[j].address) {
console.log(bombs[i].name);
} else {
console.log("non-equal elements");
}
}
}
So the first array contains objects from the google places api and the second one contains data from my database.
Thanks in advance!

You have to initialize i and j;
for (var i = 0; i < bombs.length; i++) {
for (var j = 0; j < bombsDb.length; j++) {
if (bombs[i].name === bombsDb[j].address) {
console.log(bombs[i].name);
} else {
console.log("non-equal elements");
}
}
}

Comparing can also be done using the .not selector from jquery. Check this:
var a = [1,2,3,4,5,6];
var b = [4,5,6,7,8,9];
$(a).not( $(a).not(b).get() ).get();
This will return the following array
[4,5,6]

You are missing the initial assignment to i and j in your for loop.
// here
// v
for (var i = 0; i < bombs.length; i++) {
// your loop
}
This causes the comparision to return false in the first iteration of the loop since undefined < bombs.length always return false, so it will not proceed.

Related

Make javascript variable can be empty

Hi i have this function below that removes duplicates from the variable suggest but sometimes the data i receive for the suggest variable is empty and the code below wont work beacause of the JSON.parse function how do i make it so that the variable accepts empty data so that the code below will still run without any problems. Any help would be appreciated thanks!
function suggestData(data){
var suggest = []; // I tried adding this and setting it to null but it doesn't seem to work.
suggest = JSON.parse(data);
for (var i = suggest.length - 1; i >= 0; i--) {
for (var j = 0; j < arrString.length; j++) {
if (suggest[i] === arrString[j]) {
suggest.splice(i, 1);
}
}
}
You can set suggest inside an if condition to check whether data exists or not
function suggestData(data){
var suggest = [];
if(data){
suggest = JSON.parse(data);
}
for (var i = suggest.length - 1; i >= 0; i--) {
for (var j = 0; j < arrString.length; j++) {
if (suggest[i] === arrString[j]) {
suggest.splice(i, 1);
}
}
}
Also you can simply end the function if you do not want to execute it when data is empty:
function suggestData(data) {
if(!data){
return false;
}
//other code here
...
}
Set the length conditionally as,
var length = suggest? suggest.length: 0;
function suggestData(data){
var suggest = [];
suggest = JSON.parse(data);
var length = suggest? suggest.length: 0;
for (var i = length - 1; i >= 0; i--) {
for (var j = 0; j < arrString.length; j++) {
if (suggest[i] === arrString[j]) {
suggest.splice(i, 1);
}
}
}
}
suggestData(null);
function suggestData(data){
var suggest = []; // I tried adding this and setting it to null but it doesn't seem to work.
if(data)
suggest = JSON.parse(data);
for (var i = suggest.length - 1; i >= 0; i--) {
for (var j = 0; j < arrString.length; j++) {
if (suggest[i] === arrString[j]) {
suggest.splice(i, 1);
}
}
}
Just add the if condition on parsing line like
written in above code::
if(data)
suggest = JSON.parse(data);
The simplest:
if(!data || !suggest)
return;
let array = [1,2,3,8,3,4,4,5]
const removeDuplicateItems = arr => [...new Set(arr)];
console.log(removeDuplicateItems(array))
If you just want to remove duplicated items in an array, you can instead try Set which is quite handy
Even if array is empty or null, this method removeDuplicateItems will still works

accessing all of my elements in a multi-dimensional array with multiple loops. Why is this coming out as undefined?

Here's what I have, I have a 3-dimensional array with variations of my name. The whole thing looks like this.
var array = [['kenny', 'Kenney'],['ken','Ken'],['kenneth', 'Kenneth']];
Now, there's nothing wrong with it from what I can tell but then comes what I would like to do. I'm just trying to utilize a for loop to just loop through all of this at once so all of these elements show up. Here's what I wrote down for myself..
for(var i = 0; i < array.length; i++) {
for(var j = 0; j < array.length[i]; j++) {
for(var k = 0; k < array.length[i][j]; k++) {
console.log(array[i][j][k]);
}
}
};
What comes back is undefined. What exactly am I doing wrong? Thanks in advance, guys.
You have 2 issues here. First, you are trying to go 3 "levels" deep as if this was a 3-dimensional array, but it is only 2-dimensional.
You also need to do array[i].length instead of array.length[i]
var array = [
['kenny', 'Kenney'],
['ken', 'Ken'],
['kenneth', 'Kenneth']
];
for (var i = 0; i < array.length; i++) {
for (var j = 0; j < array[i].length; j++) {
console.log(array[i][j]);
}
};
You put the indexes in the wrong spot:
for(var i = 0; i < array.length; i++) {
for(var j = 0; j < array[i].length; j++) {
for(var k = 0; k < array[i][j].length; k++) {
console.log(array[i][j][k]);
}
}
}
The last loops is not needed, because that will go through the words in each of your items, printing word for word each element.
Each element of the first array has to be treated as an array.
var array = [['kenny', 'Kenney'],['ken','Ken'],['kenneth', 'Kenneth']];
for (var i=0; i<array.length; i++) {
for (var j=0; j < array[i].length; j++) {
console.log(array[i][j]);
}
}
Using forEach is clearer:
var array = [['kenny', 'Kenney'],['ken','Ken'],['kenneth', 'Kenneth']];
array.forEach(function(subarray) {
subarray.forEach(function(name) {
console.log(name);
});
});

accessing local variable outside of for loop

I have a function
$rootScope.getCurrency = function() {
for (var i = 0; i < data.records.length; i++) {
for (var j = 0; j < data.records[i].columns.length; j++
if (data.records[i].columns[j].fieldname == "Currency") {
// Here I want to
// return the values
// if I do something like
return data.records[i].columns[j].value
// the loop exits on the first condition
// and does not iterate over completely. If I put
// return outside of the
// for loops it says i, j are undefined.
// How can I use the value outside of this loop
}
}
}
}
}
I have to use the returned value in my HTML for binding data.
My HTMl looks like:
ng-repeat i in someArray ng-if={{i.type==currency?getCurrency():''}}
Try pushing the values to an array:
$rootScope.getCurrency = function() {
var result = [];
for (var i = 0; i < data.records.length; i++) {
for (var j = 0; j < data.records[i].columns.length; j++
if (data.records[i].columns[j].fieldname == "Currency") {
// Add to array
result.push(data.records[i].columns[j].value);
}
}
}
return result;
}

Diff an Array (without modifying original arrays)

OBJECTIVE
I am trying to highlight the dfferences between two arrays. Please note that arr1 and arr2 will vary in length and have multiple types present (strings and numbers).
MY CODE
function diff(arr1, arr2) {
var diffArr = [];
if (arr1.length >= arr2.length) {
for (var i = 0; i < arr1.length; i++){
if (arr2.indexOf(arr1[i]) < 0) {
diffArr.push(arr1[i]);
}
}
} else {
for (var j = 0; j < arr2.length; j++){
if (arr1.indexOf(arr2[j]) < 0) {
diffArr.push(arr2[j]);
}
}
}
return diffArr;
}
ISSUES
diff([1, 2, 'cat', 'fish'], [1, 2, 3,'dog']); //returns only ['cat', 'fish']
I am pretty sure that my code is only returning the duplicates in one of the arrays via diffArr.push (even if there are unique values in both arrays). However, I am unsure how to overcome this.
My references
Removes Duplicates from Javascript Arrays
Removed Duplicates from an Array Quickly
Javascript Array Difference
Your code currently only crawls through one array (let's call it A) and pushes in all the A values that don't exist in B. You never go the other way and push in the B values that don't exist in A. There's also no need to have different behavior based on which array is longer. Here is the final answer in a simple way:
function diff(arr1, arr2) {
var diffArr = [];
for (var i = 0; i < arr1.length; i++) {
if (arr2.indexOf(arr1[i]) < 0) diffArr.push(arr1[i]);
}
for (var j = 0; j < arr2.length; j++) {
if (arr1.indexOf(arr2[j]) < 0) diffArr.push(arr2[j]);
}
return diffArr;
}
And in a slightly more functional way:
function diff(arr1, arr2) {
var elsIn1Not2 = arr1.filter(function(el){ return arr2.indexOf(el) < 0; });
var elsIn2Not1 = arr2.filter(function(el){ return arr1.indexOf(el) < 0; });
return elsIn1Not2.concat(elsIn2Not1);
}
Both functions return [ 'cat', 'fish', 3, 'dog' ] for your example.
function diff(arr1, arr2) {
var diffArr = {};
if (arr1.length >= arr2.length) {
for (var i = 0; i < arr1.length; i++){
if (arr2.indexOf(arr1[i]) < 0) {
diffArr[arr1[i]] = 1;
}
}
} else {
for (var j = 0; j < arr2.length; j++){
if (arr1.indexOf(arr2[j]) < 0) {
diffArr[arr2[j]] = 2;
}
}
}
return diffArr.keys();
}

how not to get out of array boundaries

I have an array and by looping I compare cell with a cell near it. I get the 'out of range' exception,
How can I fix it ?
for (var i = 0; i < array.length ; i++) {
if ((++array[i] == array[i+1])) {
alert("yes");
}
else {
alert("no");
}
}
Run your loop from for (var i=0; i<array.length -1; i++) instead (because you compare against array[i+1])
Just try with:
for (var i = 0; i < array.length - 1; i++) {}
Not sure what you had in mind but using ++ outside of a for loop is never a good idea as it can be confusing. Use another variable to point to another item in the array while looping together with a bounds checker is easier to debug and keeps loop simple.
//displays 01010
//1=2(0),2=2(1),2=4(0),4=4(1),4=5(0)
var ptr = 0;
var items = new Array (1, 2, 2, 4, 4, 5);
for (var i = 0; i < items.length; i++) {
ptr++
if(ptr >= items.length)break;
if (items[i] == items[ptr]) {
console.log(1);
}
else {
console.log(0);
}
}
//or
//displays 10001 as each value is increased then compared
//2=2(1),3=2(0),3=4(0),5=4(0),5=5(1)
ptr = 0;
for (var i = 0; i < items.length; i++) {
ptr++
if (ptr >= items.length) break;
if (++items[i] == items[ptr]) {
console.log(1);
}
else {
console.log(0);
}
}

Categories