Javascript combine and sort arrays - javascript

Beginner
I have 3 arrays, i would like to combine and sort, according to date and time.
All 3 arrays, only have date and time values.
Example:
var slackStart = []; //time the current starts for the week.
var CurrentTurn = []; //time the current turns for the week.
var slackStop = []; //time the current stops for the week.
Output slackStart (contains all starting times for the week):
[ "2017-10-24T03:15:36Z", "2017-10-24T09:13:44Z", "2017-10-24T15:41:27Z", "2017-10-24T21:40:27Z", "2017-10-25T03:47:20Z"]
I need to combine the 3 arrays and sort according to date and time. I also need to know from which array the value came. If its slackStart, i know its the starting time for the current.
I want to display it like this.
Current start: 11/11/17 12:00
Current turn: 11/11/17 14:00
Current Stop: 11/11/17 17:00
Combining the arrays is easy but how can i know from which array it came?
I tried using keys but struggled a bit.
Any help would be appreciated.

You can combine arrays simply by calling the 'concat' method:
var aryA = [1,2,3]
,aryB = [4,5,6]
,aryResult = aryA.concat(aryB);
'aryResult' will contain [1,2,3,4,5,6], in terms of identifying where it came from, are the dates going to be unique?
If not then you should forget an array and convert to an object with unique key for each entry, then you can simply use the key.
var objResult = {};
for( var idx in aryResult ) {
objResult["k" + idx] = aryResult[idx];
}
The above will translate the combined array into an object with each member having a key that starts with k followed by the array index.

Related

Replacing array value with a matching object

I'm building a react app to display esports matches from the pandascore api. I've pulled the dates of all of the matches and created a multi-layer array that groups them in to weeks.
I'm trying to replace the dates in the array that I've made with the corresponding match. This way, I can have an object with matches grouped by week.
// map an array of dates
//getting dates that we will replace
// ie ["2018-07-29T20:41:28Z", "2018-07-29T21:32:14Z", "2018-08-05T01:08:11Z"]
Object.values(groups).map((matchDateTime) => {
console.log(matchDateTime);
//loop over every date in the array
for (let d = 0; d < matchDateTime.length; d++) {
//set a variable and set it to find a match from the matches array
//that has the same date and time to the
//entry in the matchDateTime array
let matchWithDate = matches.reduce( match => {
//if dates match, then we will replace the date in the
//matchDateTime array to the match object we found
//this is the logic I'm looking for but doesn't return anything
match.begin_at = matchDateTime[d] ? matchDateTime[d] = match : 'no match';
//returns the correct date - line 71 in the screenshot
console.log(matchDateTime[d]);
//returns the correct match - line 72
console.log(match);
// returns the coresponding match date/time - line 73
console.log(match.begin_at);
}
);
}
// console.log(groups);
});
What I'm getting is an error after the loop runs a few times. There shouldn't be any dates/times that are null or undefined as I've pulled them directly from the objects I'm checking against.
I feel like I'm close. Any help is appreciated!
I altered my loop to use the filter method instead of reduce. I also edited my ternary operation to regular if logic.

Sorting high-scores in JavaScript?

Hello I am writing a game using javascript that takes the user's name as well as the "round" they made it to and stores it in two different arrays, and I would like to display the names coupled with the scores, highest to lowest but I'm stumped on how to do it, I can sort the rounds from highest to lowest but I can't figure out how to sort the names along with them. Please help!
my current code:
nameScore.push(username);
highScore.push(round);
highScore.reverse();
for (var i = 0; i < highScore.length; i++) {
$("#highScore").append(nameScore[i] + " " + highScore[i] + "<br>");
}
Don't use two arrays that are not linked in any way. Just use one array.
const userScores = [];
// Play game, get score
userScores.push({username, roundNumber, score});
Now you can search/sort this array and the username, the round number, and the score value are all linked together.
There are many suggestions in Stackoverflow on handling the synchronous sorting of several arrays. One idea that came to my mind is the creation of a sorted index array for stepping through the concerned arrays, that are left unsorted. Here is a short example with array nam, containing names and array num with the associated scores. The function mkidx(arr) expects the array to be sorted after as an argument (I chose num) and returns a sorted (in descending order) index array that can then be used to step through all unsorted arrays:
var nam=['eins','zwei','drei'];
var num=[10,200,30];
// create an index array:
const mkidx=arr=>arr.map((v,i)=>
({v,i})).sort((a,b)=> typeof a.v=="string"? a.v.localeCompare(b.v) : b.v-a.v).map(v=>v.i);
mkidx(num).forEach(k=>
console.log(k,nam[k]+': '+num[k])
)
I created the index-creation function such that it checks for the type of elements and then sorts either alphabetically (.localeCompare()) or numerically (descending).

javascript for loop and array pushing [duplicate]

This question already has answers here:
Array.push() makes all elements the same when pushing an object [duplicate]
(2 answers)
Dates changing when I change another date [duplicate]
(1 answer)
Closed 26 days ago.
I'm trying to create an array of date objects starting from a certain date up till today.
Here's the code I have:
var beginning = new Date("04,06,2013");
var dates = [];
var today = new Date();
while (beginning < today){
var x = beginning;
console.log(x);
dates.push(x);
beginning.setDate(beginning.getDate()+1)
}
for (var i in dates) {
console.log(dates[i]);
}
In the while loop I see the correct dates incrementing but when I print out the dates in the array at the last for loop I see all the dates that are pushed being today's date.
Any ideas?
What your code does is push a whole bunch of references to the exact same Date object. So, you have an array full of all the same Date object and each time you change that object, all elements in the array just point to the same object so they will all appear to change.
When you push an object into an array or assign an object to a variable, it does not make a copy, it pushes a reference to it (think of it like a pointer in other languages). To push different date objects for each iteration of the loop, you'd have to create a new date object each time through the loop and push that.
In javascript, assigning an object or an array to any variable (which includes pushing it into an array) only assigns a reference to that object or array, not a copy. This is a common issue that bits most people coming up to speed on javascript.
You can make a new date object each time through the loop like this:
var beginning = new Date("04,06,2013");
var dates = [];
var today = new Date(), x;
while (beginning < today){
x = new Date(beginning.getTime());
console.log(x);
dates.push(x);
beginning.setDate(beginning.getDate()+1)
}
You're only working with one single Date instance throughout all that code.
To create a copy of a Date, do this:
x = new Date(beginning.getTime());
Then call the .setDate() method to move it forward.
The setters on JavaScript Date instances change the object. They don't create a new one.

Which javascript structure has a faster access time for this particular case?

I need to map specific numbers to string values. These numbers are not necessarily consecutive, and so for example I may have something like this:
var obj = {};
obj[10] = "string1";
obj[126] = "string2";
obj[500] = "string3";
If I'm doing a search like this obj[126] would it be faster for me to use an object {} or an array []?
There will be no difference. ECMAScript arrays, if sparse (that is don't have consecutive indices set) are implemented as hash tables. In any case, you are guaranteed the O(n) access time, so this shouldn't concern you at all.
I created a microbenchmark for you - check out more comprehensive test by #Bergi. On my browser object literal is a little bit slower, but not significantly. Try it yourself.
A JS-array is a object, so it should not matter what you choose.
Created a jsperf test (http://jsperf.com/array-is-object) to demonstrate this.
Definetely an object should be the best choice.
If you have such code:
var arr = [];
arr[10] = 'my value';
, your array becomes an array of 11 values
alert(arr.length); // will show you 11
, where first 10 are undefined.
Obviously you don't need an array of length 1000 to store just
var arr = [];
arr[999] = 'the string';
Also I have to notice that in programming you have to chose an appropriate classes for particular cases.
Your task is to make a map of key: value pairs and object is the better choice here.
If your task was to make an ordered collection, then sure you need an array.
UPDATE:
Answering to your question in comments.
Imagine that you have two "collections" - an array and an object. Each of them has only one key/index equal to 999.
If you need to find a value, you need to iterate through your collection.
For array you'll have 999 iterations.
For object - only one iteration.
http://jsfiddle.net/f0t0n/PPnKL/
var arrayCollection = [],
objectCollection = {};
arrayCollection[999] = 1;
objectCollection[999] = 1;
var i = 0,
l = arrayCollection.length;
for(; i < l; i++) {
if(arrayCollection[i] == 1) {
alert('Count of iterations for array: ' + i); // displays 999
}
}
i = 0;
for(var prop in objectCollection) {
i++;
if(objectCollection[prop] == 1) {
alert('Count of iterations for object: ' + i); // displays 1
}
}
​
Benchmark
​
In total:
You have to design an application properly and take into account possible future tasks which will require some different manipulations with your collection.
If you'll need your collection to be ordered, you have to chose an array.
Otherwise an object could be a better choice since the speed of access to its property is roughly same as a speed of access to array's item but the search of value in object will be faster than in sparse array.

storing a dynamic array of values inside an object looped within a for statement

I am looking to create a set of dynamically created arrays stored inside an object. the outcome would be something similar to this...
object.array0.length = 5, object.array1.length = 4, etc
the name of the array would be generated from within a for loop based on a numerical value declared elsewhere in the application.
Here is the code that I have...
var obj = {};
var weekNum = 4;
for(i=0; i < weekNum.length;i++) {
obj['week'+i] = [];
obj['week'+i].push(day);
console.log('days stored in week0: '+obj.week0.length);
}
What seems to be happening is that obj['week'+i] doesn't realize that it is an array, and the push command doesn't seem to be enough to make it think so. So as a resulting value of obj.week0.length is always 1 with the actual value just being replaced each time as opposed to the array being incremented.
Also fyi,
The parameter day in the above code would be passed in from another function representing any chosen day (Mon, Tues, etc)... However, the sequence and the amount of days passed in could differ but will never exceed 5 (m-f).
Looks like a logic problem to me. You're always only inserting 1 day into the array unless day represents something else altogether.
var obj = {};
var weekNum = 4;
// var was missing :)
for(var i = 0; i < weekNum.length; i++) {
// check if entry exists before creating new.
obj['week'+i] = obj['week'+i] || [];
// you're always only inserting 1 value inside the week array
// don't you want to loop through the number of days
// and insert a day entry for *this* week for each day. like this?
// days is another array of, hmm.. days
for(var j = 0; j <days.length; j++) {
obj['week'+i].push(days[j]);
}
console.log('days stored in week0: '+obj.week0.length);
}
It is not changing, because each time through the loop you reset the value to [], then push onto it. Try moving the obj['week'+i] = [] to outside the loop.

Categories