Find missing element by comparing 2 2D-Arrays in Javascript - javascript

A few days ago I posted a thread asking on how to find the missing element when passing a method 2 JS arrays. As you can see here. I've been trying to figure out now how to modify the method so that instead of passing it 2 Arrays you pass it 2 2D-Arrays... Having some trouble though:
/*var sml = new Array();
sml[0] = new Array("dean","22");
sml[1] = new Array("james","31");
sml[2] = new Array("ludwig","35");
var lrg = new Array();
lrg[0] = new Array("dean","22");
lrg[1] = new Array("james","31");
lrg[2] = new Array("ludwig","35");
lrg[3] = new Array("kevin","23");
lrg[4] = new Array("elton","40");*/
var sml = new Array();
sml[0] = "dean";
sml[1] = "james";
sml[2] = "ludwig";
var lrg = new Array();
lrg[0] = "dean";
lrg[1] = "james";
lrg[2] = "ludwig";
lrg[3] = "kevin";
lrg[4] = "elton";
var deselected = findDeselectedItem(sml, lrg);
alert("Deselected Items: " + deselected[0]+", "+ deselected[1]);
// -------------------------------------------------------------- //
function findDeselectedItem(CurrentArray, PreviousArray) {
var CurrentArrSize = CurrentArray.length;
var PreviousArrSize = PreviousArray.length;
var deselectedItems = new Array();
// loop through previous array
for (var j = 0; j < PreviousArrSize; j++) {
// look for same thing in new array
if (CurrentArray.indexOf(PreviousArray[j]) == -1)
deselectedItems.push(PreviousArray[j]);
}
if (deselectedItems.length != 0) {
return deselectedItems;
} else {
return null;
}
}​
Now if you run the above code it works perfectly, but if you go and uncomment the variable declarations on top that that pushes arrays ontop of the array, and then comment out the simple strings that get pushed on top of the array, it doesn't work as well... For instance:
var sml = new Array();
sml[0] = new Array("dean","22");
sml[1] = new Array("james","31");
sml[2] = new Array("ludwig","35");
var lrg = new Array();
lrg[0] = new Array("dean","22");
lrg[1] = new Array("james","31");
lrg[2] = new Array("ludwig","35");
lrg[3] = new Array("kevin","23");
lrg[4] = new Array("elton","40");
/*var sml = new Array();
sml[0] = "dean";
sml[1] = "james";
sml[2] = "ludwig";
var lrg = new Array();
lrg[0] = "dean";
lrg[1] = "james";
lrg[2] = "ludwig";
lrg[3] = "kevin";
lrg[4] = "elton";*/
var deselected = findDeselectedItem(sml, lrg);
alert("Deselected Items: " + deselected[0]+", "+ deselected[1]);
// -------------------------------------------------------------- //
function findDeselectedItem(CurrentArray, PreviousArray) {
var CurrentArrSize = CurrentArray.length;
var PreviousArrSize = PreviousArray.length;
var deselectedItems = new Array();
// loop through previous array
for (var j = 0; j < PreviousArrSize; j++) {
// look for same thing in new array
if (CurrentArray.indexOf(PreviousArray[j][0]) == -1)
deselectedItems.push(PreviousArray[j][0]);
}
if (deselectedItems.length != 0) {
return deselectedItems;
} else {
return null;
}
}​
The method returns 2 completely wrong values. PS - I'm not interested in the "numbers" just yet, just the "names" for now...

Your CurrentArray is 2-dimensional and indexOf compares Arrays but not first elements of that Arrays. So you need to use:
for ( var i = 0; i < CurrentArray.length; ++i){
if (CurrentArray[i][0] == PreviousArray[j][0]){
deselectedItems.push(PreviousArray[j][0]);
break;
}
}
Instead of
if (CurrentArray.indexOf(PreviousArray[j][0]) == -1)
deselectedItems.push(PreviousArray[j][0]);

You could also rearrange the array like this:
var sml = {};
sml["dean"] = 22;
sml["james"] = 31;
sml["ludwig"] = 35;
var lrg = {};
lrg["dean"] = 22;
lrg["james"] = 31;
lrg["ludwig"] = 35;
lrg["kevin"] = 23;
lrg["elton"] = 40;
and use:
function findDeselectedItem(c,p){
ret=[];
for (var i in p){
if (p.hasOwnProperty(i)){
if ('undefined'===typeof c[i]) {
ret.push(i);
}
}
}
return ret;
}
alert(findDeselectedItem(sml, lrg));
Demo: http://jsfiddle.net/LsrCj/

indexOf function will check object equality in this case; to make it return something else than -1 you've to pass same 2D array instances to sml and lrg.
new Array("dean","22") === new Array("dean","22") //false
Keep the same instances (e.g. http://jsfiddle.net/3TQYz/) in both arrays or use your own indexOf test that would recursively check values of the array to make your case working.

Related

Push Objects into an array in Jquery

I'm trying to fill an array with objects, but the array is not filling properly. The last value is set in all positions of the array. Here's the code:
var matrixprice = 5;
var qualifiedDate = '2019-10-01';
var today = new Date();
var qDate = new Date(qualifiedDate);
var nextDay = qDate;
var myObject = new Object();
var myArray = [];
var dailybonus = matrixprice * 0.03;
var full_bonus = matrixprice * 2;
var i = 0;
while (i <= full_bonus) {
nextDay.setDate(nextDay.getDate() + 1);
i += dailybonus;
myObject.title = '$' + i;
myObject.start = nextDay;
myArray.push(myObject);
}
var myString = JSON.stringify(myArray);
console.log(myString);
The array Im getting is filled with only 1 value in all positions it looks like this:
[{"title":"$100.5","start":"2020-01-03T18:50:23.000Z"}, {"title":"$100.5","start":"2020-01-03T18:50:23.000Z"},{"title":"$100.5","start":"2020-01-03T18:50:23.000Z"},{"title":"$100.5","start":"2020-01-03T18:50:23.000Z"},{"title":"$100.5","start":"2020-01-03T18:50:23.000Z"},{"title":"$100.5","start":"2020-01-03T18:50:23.000Z"}]
Thank you in advance!
Update your while loop to push a new object:
while(i <= full_bonus){
nextDay.setDate(nextDay.getDate()+1);
i += dailybonus;
myArray.push({title: '$'+i, start: new Date(nextDay)});
}
Here's the full, working example:
var matrixprice = 5;
var qualifiedDate = '2019-10-01';
var today = new Date();
var qDate = new Date(qualifiedDate);
var nextDay = qDate;
var myArray = [];
var dailybonus = matrixprice * 0.03;
var full_bonus = matrixprice * 2;
var i = 0;
while(i <= full_bonus){
nextDay.setDate(nextDay.getDate()+1);
i += dailybonus;
myArray.push({title: '$'+i, start: new Date(nextDay)});
}
var myString = JSON.stringify(myArray);
console.log(myString);

How do I delete an array inside an array?

I want to delete an array entry.
I have already used the splice method, but it doesn't work.
var clients = new Array();
//-----
var tmp = new Array();
tmp["connection"] = connection;
tmp["authentificated"] = 1;
tmp["username"] = rows[0].username;
tmp["rank"] = rows[0].rank;
clients.push(tmp);
This doesn't work:
clients.splice(index, 1);
Do you have any ideas, where the mistake is?
Thanks in advance.
you can use like below.
var clients = new Array();
var tmp = new Array();
tmp["connection"] = "hi";
tmp["authentificated"] = 1;
clients.push(tmp);
var tmp1 = new Array();
tmp1["connection"] = "hi";
tmp1["authentificated"] = 2;
clients.push(tmp1);
var index = 0;
delete clients[index];
console.log(clients);
but the issue with delete is that the length of the array will remain same because delete only removes the object from the element in the array

XYZ dimensional array

Why is this code shown array[7][0] is undefined when it should have a value?
var tnotes = [];
var index = 0;
for (var i = 0; i < 14; i++) {
tnotes[i] = [];
}
var tx = 'B4';
var notes=['B5','A5','G5','F5','E5','D5','C5','B4','A4','G4','F4','E4','D4','C4']
var getNotes = notes.indexOf(tx);
if (getNotes != -1) {
tnotes[getNotes][index][] = new Array(20)
tnotes[getNotes][index][0] = tx //B4
tnotes[getNotes][index][2] = '3sec'
index++
}
console.log(tnotes[7][0])
You simply have a syntax error in defining one of your sub-arrays. The following line is incorrect:
tnotes[getNotes][index][] = new Array(20)
You are introducing a third-dimension of your tnotes array without it being defined
It should be:
tnotes[getNotes][index] = [];
Or if you really need the size parameter:
tnotes[getNotes][index] = new Array(20);
After this, tnotes[7][0] should no longer be undefined. Also, please do yourself a favor and make sure you use semi-colons consistently, it's good practice and can save you many-a-headache.
Corrected code:
var tnotes = [];
var index = 0;
for (var i = 0; i < 14; i++) {
tnotes[i] = [];
}
var tx = 'B4';
var notes = ['B5','A5','G5','F5','E5','D5','C5','B4','A4','G4','F4','E4','D4','C4'];
var getNotes = notes.indexOf(tx);
if (getNotes != -1) {
tnotes[getNotes][index] = [];
tnotes[getNotes][index][0] = tx; //B4
tnotes[getNotes][index][2] = '3sec';
index++;
}
console.log(tnotes[7][0]);

scope of 3 dimensional array in javascript?

I'm trying to create a 3 dimensional array dynamicall in javascript based on a flat array of objects. after looping through the array, the array seems empty. If I print while in the loop, it seems to work, but then it seems to be gone and I want to return this to the caller. Help ?
//init the 3d array ??
this.teams = [];
for(var i = 0; i < sportsStandings.length; i++) {
var item = sportsStandings[i];
if(!this.teams[item.league])
this.teams[item.league] = new Array();
if(!this.teams[item.league][item.division])
this.teams[item.league][item.division] = new Array();
this.teams[item.league][item.division][this.teams[item.league][item.division].length]
= new Team(item.teamName, item.wins, item.losses);
console.log(this.teams); //this prints properly, and i see the 3d array grow
}
console.log('second' + this.teams); //this prints nothing
I cleaned up the code a bit, there is a couple of other ways to write it.
this.teams = [];
var teams = this.teams;
for(var i = 0; i < sportsStandings.length; i++) {
var ss = sportsStandings[i],
league = ss.league,
division = ss.division,
teamName = ss.teamName,
wins = ss.wins,
losses = ss.losses;
if (!teams[league]) {
teams[league] = {};
teams[league][division] = [];
} else if (!teams[league][division]) {
teams[league][division] = [];
}
var newTeam = new Team(teamName, wins, losses);
teams[league][division].push(newTeam);
}

Can't add to javascript array in loop

I'm having some issues with the following code:
var tmpArray = new Array();
for(var n in fnlArray){
if(fnlArray[n] == largest.val){
alert(fnlArray[n] +"-"+ largest.val);
tmpArray[n] = fnlArray[n];
}
}
fnlArray contents is:
fnlArray['result1'] = 1;
fnlArray['result2'] = 2;
fnlArray['result3'] = 2;
fnlArray['result4'] = 2;
and largest.val = 2;
The issue I'm having is the alert gets fired so I would expect to end up with tmpArray with the following:
tmpArray['result2'] = 2;
tmpArray['result3'] = 2;
tmpArray['result4'] = 2;
But the array (tmpArray) is always empty. Is this an issue with adding items to the array dynamically within a loop?
var tmpArray = new Array(); should be:
var tmpArray = {};
Your tmpArray object is not a index array, so you have to use object literals.
var tmpArray = {};
for(var n in fnlArray){
if(fnlArray[n] == largest.val){
tmpArray[n] = fnlArray[n];
}
}
alert(JSON.stringify(tmpArray)); //Prints: {"result2":2,"result3":2,"result4":2}
Demo: http://jsfiddle.net/QhFGF/

Categories