Sorting parallel arrays in javascript - 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.

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.

How can i push a array in another array?

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/

Javascript - Associative Arrays not working?

So I have csv files that basically include lists of students, what school they are in, and what subjects they are taking(ex. chem, spanish, biology, etc). I want to have my program let the user type in a subject area(s) and have the page return the amount of times each subject is being taken.
I then have some javascript that basically takes in some user input from a text field, parse that, and puts it into an array. Then, it imports the csv file and compares the subject columns to what the user inputs, and calculates the amount of time each subject is taking.
My javascript looks like this:
var globalArray = [];
var schoolList = [];
var splitTextInput = [];
var count = 0;
var splitSubjectArea = [];
function myFunction()
{
var textInput = document.getElementById('numb').value;
var needsTrimTextInput = textInput.split(","); //creating an array to store user input
for( var q = 0; q < needsTrimTextInput.length; q++) //getting rid of whitespace in user input
{
splitTextInput[q] = needsTrimTextInput[q].trim();
}
for(var j = 0; j< splitTextInput.length; j++)
{
var sSubjectArea = {};
sSubjectArea[ splitTextInput[j] ] = 0; //assigning the value to 0 to store the count of each subject
}
var fileName = document.getElementById("UniversitySelect").value;
if( fileName.indexOf(".csv") > 0 )
{
d3.csv( "./" + document.getElementById("UniversitySelect").value, bob, counting);
}
function bob(d){
return { Area: d.Area };
}
function counting(error, rows)
{
globalArray = rows;
for( var i = 0; i < rows.length; i++ ) //for the row in the CSV file
{
for( var k = 0; k < splitTextInput.length; k++ ) // loop to go through the different inputed subject areas
{
if( rows[i].Area.toLowerCase().indexOf( splitTextInput[k].toLowerCase() ) > -1)
{
count++; //stores the overall count
sSubjectArea[splitTextInput[k]] += 1;
//console.log(sResearchArea[splitTextInput[k]]);
}
}
}
console.log(rows);
for(r = 0; r < splitTextInput.length; r++)
{
console.log( sSubjectArea[ splitTextInput[r] ] );
}//for
}//function
}//function
I know it partially works, because if I enter in 2 subjects, say Chemistry and Biology, which are taken 3 times each, then the count will be 6. However, I cannot get sSubjectArea to hold the count for each individual subject. What am I doing wrong? When I added the console.log(sSubjectArea[splitTextInput[k]]) line, the output I get is:
1
NaN
2
3
4
NaN
5
6
Array [ Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, 86 moreā€¦ ]
NaN
6
And I don't really understand why I get those numbers & especially NaN.... can anyone help? I'm really new to javascript, so I might have made some sort of fundamental error in understanding objects, but I can't figure it out. Any help would be much appreciated, thanks!!

I'm having difficulty populating a two dimensional array with random Boolean values and then reading those values back out in JavaScript

I'm working on a really simple cellular automata program in JavaScript. For right now I just want to write a bunch of random Boolean values to a two-dimensional array and then read that array back to be manipulated or displayed in some way.
var dimension = 5;
var grid = new Array();
for (x = 0; x < dimension; x++) {
grid[x] = new Array();
}
//populate grid
for (i = 0; i < dimension; i++) {
document.write('<br>');
for (j = 0; j < dimension; j++) {
grid[i,j] = Math.floor(Math.random()*2);
document.write(grid[i,j]);
}
}
for (i = 0; i < dimension; i++) {
document.write('<br>');
for (j = 0; j < dimension; j++) {
document.write(grid[i,j]);
}
}
So, I've whittled the code down to a few nested for loops where I cycle through and populate the array and then print it back. Note that the output generated during the population loop is what I want, random values. But when I read the array back, it seems like the last row (I think it's really a column, but it's displayed horizontally) has been copied to all the others...
I've done this sort of thing before in other languages and never had a problem like this.
I'm new to this community and JavaScript in general so this might be a dumb questing or I may not have presented it helpfully. I would really appreciate any help or advice on how I can improve my question.
Array indexes in JavaScript are not comma seperated. You need to use brackets. So for your two dimensional array it will be:
grid[i][j]; // not grid[i,j]

Categories

Resources