How can i push a array in another array? - javascript

i have a main array with 64 positions, for each position i need another array. like: someArray[index] = [someObject].
How can i create those arrays ? and How can i get someObject.name , someObject.lastName ?
Here is the code:
$scope.filaCores = [];
$scope.object = {}
$scope.object.name = "name";
$scope.object.secondname= "secondname";
for(var i = 0; i <10; i++) {
$scope.filaCores[i] = [$scope.object.name, $scope.object.secondname];
}

Here you go: https://jsfiddle.net/jsg81gg8/1/
Based on your description I do not see the need for an array of arrays. But since that is what you asked for here you go. You didn't specify how many array elements for the sub array so I'm going to show an example with three. If you only need 64 total structures then the inner array is not needed.
window.getRandomInt = function() {
return Math.floor(Math.random() * (10000 - 1 + 1)) + 1;
}
mainArray = []; /* you said you wanted 64 of these */
subArray = []; /* you didn't specify how many of these, the example below will assume 3 per each mainarray */
for (i = 0; i < 64; i++) {
for (j = 0; j < 3; j++) {
/* I'm using getRandomInt() just so you can see all the names are different */
subArray[j] = {name:"John"+getRandomInt(), lastname:"Doe"+getRandomInt()};
}
mainArray[i] = subArray;
}
/* Press F12 and go to the console tab, run this script, and you will see the output of the entire array */
console.log(mainArray);
/* You can access a specific element like this... */
alert('Alerting mainArray[23][2].lastname: '+mainArray[23][2].lastname);
If you really don't need the sub array, and you only need 64 structures then it could be simplified to look like this: https://jsfiddle.net/Ldafbwbk/1/
UPDATE: And here is a third example that more closely resembles your updated question: https://jsfiddle.net/7st8fnw5/3/

Related

Creating new array from unique elements found in array

I was given an assignment:
Finding unique elements in an array and creating a new array from these unique elements.
The professor gave us the pseudocode to code this assignment - it should be straightforward but my code is not working.
Here is my attempt:
// search for unique birthdays in the array
function find(birthdays) {
var uniqueBirthdays = [];
for (var i = 1; i <= birthdays.length; i = i + 2) {
var count = 0;
for (var j = 1; j <= birthdays.length; j = j + 2) {
if (birthdays[i] == birthdays[j]) {
count++;
}
}
if (count == 1) {
var n = uniqueBirthdays.length;
uniqueBirthdays[n] = birthdays[i - 1];
}
}
return uniqueBirthdays;
}
I have tried checking for indentation errors as well as a number of other things but can not figure out why as the array is traversed it is giving each element a count of only 1 (meaning there are no matching elements) - it does not seem to be traversing the array more than once so no elements have a count greater than 1 - even though I am using nested for loops.
I have increased the intervals by 2 because I need to compare every other element - there is a number assigned to each birthday so the array may look like:
['0001'][12/15]['0002'[03/12]...
I am brand new so I may be overlooking simple but ive tried so many things and i can not understand why this code isnt working - it is returning back all of the elements that are assigned to the birthdays instead of just the unique ones.
Any help that will point me in the right direction is very much appreciated.
You were very close, and there were just a couple mistakes. The only things that did not work were the way you wrote your for loops:
for (var i = 1; i <= birthdays.length; i = i + 2) {
Array indexes start at 0, so if you want to process the first element, use var i = 0;
Since these indexes start at 0, for an Array of 3 elements, the last index is 2. So you only want to run your loop while i is less than the array length: i < birthdays.length
You were skipping elements by doing i = i + 2. There seems to be no reason for it?
Something else worth mentionning: in JS, indentation does not matter - well, it does, but only to avoid making your eyes bleed. In fact, most websites use minified versions of their code, which fits on a single (often very long and ugly) line (example).
Here is your code, with only two lines fixed:
function find(birthdays) {
var uniqueBirthdays = [];
for (var i = 0; i < birthdays.length; i = i + 1) { // <-----
var count = 0;
for (var j = 0; j < birthdays.length; j = j + 1) { // <-----
if (birthdays[i] == birthdays[j]) {
count++;
}
}
if (count == 1) {
var n = uniqueBirthdays.length;
uniqueBirthdays[n] = birthdays[i];
}
}
return uniqueBirthdays;
}
// I used letters instead of birthdays for easier demo checking
var birthdays = ['a', 'b', 'a', 'c'];
console.log( find(birthdays) ); // ["b", "c"]
JS have direct methods tor that use Array.indexOf(), Array.lastIndexOf() and Array.filter()
uniques elements have same first position and last position
sample code:
const initailArray = [...'ldfkjlqklnmbnmykdshgmkudqjshmjfhmsdjhmjh']
const uniqueLetters = initailArray.filter((c,i,a)=>a.indexOf(c)===a.lastIndexOf(c)).sort()
console.log(JSON.stringify(uniqueLetters))

javascript thinks the values in two arrays don't match even though they do

This snippet of code is throwing me for a loop.
if(colList[i] != checkList[i]) {
var colTest = colList[i];
var checkTest = checkList[i];
As you can see from this screenshot from the debug the values are identical.
ScreenShot
Any hints as to why the if statement thinks these values are different?
EDIT: Here is a screenshot showing the full arrays.
Again, I'm not sure why this matters. In fact for testing purposes I have both arrays pulling from the exact same source data.
2nd Edit:
Here is all the relevant code. Again, as you can see the arrays are identical.
var colList = sheet.getRange(startRow,watchCol,lastRow,1).getValues(); // Data set with all values to watch
var checkList = sheet.getRange(startRow,watchCol,lastRow,1).getValues(); // Data set with all the check values
function timeStamp() {
for(var i = 0; i <= colList.length; i++)
if(colList[i] != checkList[i]) {
return colList
return checkList
Here is the full code that is trying to treat it as a multidimensional array. This code does not work and returns "Cannot read property "0" from undefined. (line 13,"
var sheet = SpreadsheetApp.getActive().getSheetByName("Sheet1");
var startRow = 2; // First row with Data
var lastRow = sheet.getLastRow() - startRow;
var watchCol = 2; // Column to check for changes
var checkCol = 7; // Column to check against
var timeCol = 3; // Column to put the time stamp in
var colList = sheet.getRange(startRow,watchCol,lastRow,1).getValues(); // Data set with all values to watch
var checkList = sheet.getRange(startRow,watchCol,lastRow,1).getValues(); // Data set with all the check values
function timeStamp() {
for(var i = 0; i <= colList.length; i++)
for(var j = 0; j < checkList.length; j++){
if(colList[i][j] != checkList[i][j]) {
return colList
return checkList
sheet.getRange(i + startRow,checkCol).setValue(colList[i]);
sheet.getRange(i + startRow,timeCol,1,1).setValue(new Date());
}
}
}
According to your screenshots it's simple.
Your's arrays doesn't contain strings, they contain array that contain string, and thus to compare is true, because two arrays will always be different, that because arrays in js are objects and when you try to compare objects it compares that references of them , not the value.
So you should make array of strings, or just to add [0] to each side in the if
As I said in the comment, you have that one index arrays inside another array, so yours are multi-dimensional arrays and you have to use 2 indexes to access its values, i = row and j = column
var checkList = [["Beef"], ["Red"], ["Career"], ["Chicken"], ["Red"], ["Kids"], ["Beef"], ["Red"]];
var colList = [["Beef"], ["Red"], ["Career"], ["Chicken"], ["Red"], ["Kids"], ["Beef"], ["Red"]];
function timeStamp() {
for(var i = 0; i < colList.length; i++){
for(var j = 0; j < checkList[i].length; j++){
if(colList[i][j] != checkList[i][j]) {
console.log('not equal');
} else{
console.log('equal');
}
}
}
}
timeStamp();
As it turns out adding .String() at the end of the function creating the arrays fixed the issue and allowed them to compare correctly.

Manipulate more javascript array based on another array

I've a strange thing to do but I don't know how to start
I start with this vars
var base = [1,1,1,2,3,5,7,9,14,19,28,40,56,114,232,330];
var sky = [0,0,0,3,4,5,6,7,8,9,10,11,12,14,16,17];
var ite = [64,52,23,38,13,15,6,4,6,3,2,1,2,1,1,1];
So to start all the 3 array have the same length and the very first operation is to see if there is a duplicate value in sky array, in this case the 0 is duplicated and only in this case is at the end, but all of time the sky array is sorted. So I've to remove all the duplicate (in this case 0) from sky and remove the corresponding items from base and sum the corresponding items on ite. So if there's duplicate on position 4,5 I've to manipulate this conditions. But let see the new 3 array:
var new_base = [1,2,3,5,7,9,14,19,28,40,56,114,232,330];
var new_sky = [0,3,4,5,6,7,8,9,10,11,12,14,16,17];
var new_ite = [139,38,13,15,6,4,6,3,2,1,2,1,1,1];
If you see the new_ite have 139 instead the 64,52,23, that is the sum of 64+52+23, because the first 3 items on sky are the same (0) so I remove two corresponding value from base and sky too and I sum the corresponding value into the new_ite array.
There's a fast way to do that? I thought a for loops but I stuck at the very first for (i = 0; i < sky.length; i++) lol, cuz I've no idea on how to manipulate those 3 array in that way
J
When removing elements from an array during a loop, the trick is to start at the end and move to the front. It makes many things easier.
for( var i = sky.length-1; i>=0; i--) {
if (sky[i] == prev) {
// Remove previous index from base, sky
// See http://stackoverflow.com/questions/5767325/how-to-remove-a-particular-element-from-an-array-in-javascript
base.splice(i+1, 1);
sky.splice(i+1, 1);
// Do sum, then remove
ite[i] += ite[i+1];
ite.splice(i+1, 1);
}
prev = sky[i];
}
I won't speak to whether this is the "fastest", but it does work, and it's "fast" in terms of requiring little programmer time to write and understand. (Which is often the most important kind of fast.)
I would suggest this solution where j is used as index for the new arrays, and i for the original arrays:
var base = [1,1,1,2,3,5,7,9,14,19,28,40,56,114,232,330];
var sky = [0,0,0,3,4,5,6,7,8,9,10,11,12,14,16,17];
var ite = [64,52,23,38,13,15,6,4,6,3,2,1,2,1,1,1];
var new_base = [], new_sky = [], new_ite = [];
var j = -1;
sky.forEach(function (sk, i) {
if (!i || sk !== sky[i-1]) {
new_ite[++j] = 0;
new_base[j] = base[i];
new_sky[j] = sk;
}
new_ite[j] += ite[i];
});
console.log('new_base = ' + new_base);
console.log('new_sky = ' + new_sky);
console.log('new_ite = ' + new_ite);
You can use Array#reduce to create new arrays from the originals according to the rules:
var base = [1,1,1,2,3,5,7,9,14,19,28,40,56,114,232,330];
var sky = [0,0,0,3,4,5,6,7,8,9,10,11,12,14,16,17];
var ite = [64,52,23,38,13,15,6,4,6,3,2,1,2,1,1,1];
var result = sky.reduce(function(r, n, i) {
var last = r.sky.length - 1;
if(n === r.sky[last]) {
r.ite[last] += ite[i];
} else {
r.base.push(base[i]);
r.sky.push(n);
r.ite.push(ite[i]);
}
return r;
}, { base: [], sky: [], ite: [] });
console.log('new base:', result.base.join(','));
console.log('new sky:', result.sky.join(','));
console.log('new ite:', result.ite.join(','));
atltag's answer is fastest. Please see:
https://repl.it/FBpo/5
Just with a single .reduce() in O(n) time you can do as follows; (I have used array destructuring at the assignment part. One might choose to use three .push()s though)
var base = [1,1,1,2,3,5,7,9,14,19,28,40,56,114,232,330],
sky = [0,0,0,3,4,5,6,7,8,9,10,11,12,14,16,17],
ite = [64,52,23,38,13,15,6,4,6,3,2,1,2,1,1,1],
results = sky.reduce((r,c,i) => c === r[1][r[1].length-1] ? (r[2][r[2].length-1] += ite[i],r)
: ([r[0][r[0].length],r[1][r[1].length],r[2][r[2].length]] = [base[i],c,ite[i]],r),[[],[],[]]);
console.log(JSON.stringify(results));

Javascript get random variables from array but each just once

I´d like to get random variables from a javascript and prepend it to a div container like that:
// my Array
var thumbnailArray = new Array();
thumbnailArray[0] = 'contentarray1';
thumbnailArray[1] = 'contentarray2';
thumbnailArray[2] = 'contentarray3';
function thumbnailquery () {
for (var i = 0; i <= 3; i++) {
$('#myDiv').prepend(thumbnailArray[Math.floor(Math.random() * thumbnailArray.length)])
}
}
Now how can i ensure that each variable is only taken once but still randomly?
Thank You
Shuffle the array and pop of values instead
function shuffle(a) {
var c=a.length,t,r;
while (0 !== c) {
r = Math.floor(Math.random() * c);
c -= 1;t = a[c];a[c] = a[r];a[r] = t;
}
return a;
}
var thumbnailArray = [
'contentarray1',
'contentarray2',
'contentarray3'
];
shuffle( thumbnailArray );
thumbnailquery();
function thumbnailquery () {
for (var i = 0; i <= 3; i++) {
$('#myDiv').prepend( thumbnailArray.pop() );
}
}
FIDDLE
Copy the array. Then delete objects that you took from the copied array.
There's no elegant way to do it the way you describe. You could construct an array of "selected indices" and ensure that each random number didn't already exist in that array, but that has a worst case operating time of infinity so highly not recommended.
Your best bet would be to shuffle the array and then iterate over, selecting the elements in order (shuffled order).
See this Stack Overflow for a good way to shuffle an array in JavaScript
How can i shuffle an array in JavaScript?
Use splice() http://www.w3schools.com/jsref/jsref_splice.asp
randNum = thumbnailArray[Math.floor(Math.random() * thumbnailArray.length)]
$('#myDiv').prepend(splice(randNum,1))

Sorting parallel arrays in javascript

I have a couple of parallel arrays called names and sales. I have the user enter up to 100 salespeople (names, obviously) and their sales. I have no problem printing these to a table. The catch (for me, anyway) is that they need to be sorted in descending order according to sales. I have made a function called sort which is coded (poorly - as I am just beginning to learn JavaScript) as:
function sort(names, sales) {
var i = 0;
var j = 0;
var temp = 0;
for (var i = 0; i < sales.length - 1; i++) {
var min = i;
for (var j = i + 1; j < array.length; j++)
if (sales[j] < (sales[min])) min = j;
temp = sales[i];
sales[i] = sales[min];
sales[min] = temp;
temp = names[i];
names[i] = names[min];
names[min] = temp;
}
}
I am in need of some help here, obviously. Can anyone lend a hand to point out the (no doubt numerous) errors?
We have been instructed to write our own sort. Sales and names are input through two different functions (getName() and getSales()) using prompts.
First, why not use a single two-dimensional array, say, SalesArray, for example:
[ ['someName', 'someSale'],
['someName2', 'someSale2'],
]
Next, simply inspect SalesArray[i][1] while sorting.
As for sorting, try implementing bubblesort, especially if you're new to sorting algorithms.
Why not just store both the name and sales in a single object? Then everything is in one array.
// Declare array
var people = new Array();
// Somewhere in a loop to add people...
var person = {
name: "jdmichal",
sales: 1000
};
people.push(person);
// Now sort based on the sales property in each object.

Categories

Resources