Parse two arrays to check each value JavaScript - javascript

So i have two lists.
List A contains a list of all dates of a specified month. list B contains a sequence of 1 and 0´s. If i want to check if date from list A is equal to 1 or 0 corresponding to the position in list B, How should i approach this?.
The idea is to check if day 1,2,3.. and so on is value 1 or 0 from List B..
Example 2020-02-01 = 1 or 0...
var listDate = [];
var startDate ='2020-02-01';
var endDate = '2020-02-29';
var dateMove = new Date(startDate);
var strDate = startDate;
while (strDate < endDate){
var strDate = dateMove.toISOString().slice(0,10);
var dayCount = listDate.length;
listDate.push(strDate);
dateMove.setDate(dateMove.getDate()+1);
};
console.log(dayCount + 1)
console.log(listDate)
Then i have another list that contains a sequence of 1 and 0 ´s.
var str = "1100000110000011000001100000100";
var res = str.split("");
var n = str.length;
console.log(n)
console.log(res)

listDate.filter((_,i) => str[i]==='1')
will give you the dates where you have a 1 in the 'binary list'
listDate.map((date,i) => [date,str[i]])
will give you a new list with sublists [date,"1 or 0"]
listDate.map((date,i) => [date,str[i]==='1'])
will give you a new list with sublists [date,true or false]

Like this?
const res = "1100000110000011000001100000100".split("");
var listDate = [];
var startDate ='2020-02-01';
var endDate = '2020-02-29';
var dateMove = new Date(startDate);
var strDate = startDate;
while (strDate < endDate){
var strDate = dateMove.toISOString().slice(0,10);
var dayCount = listDate.length;
listDate.push(strDate);
dateMove.setDate(dateMove.getDate()+1);
};
// code based on day number rather than the place in the array
listDate.forEach(dt => console.log(dt,res[dt.split("-")[2]-1]))
let weekdays = listDate.filter(dt => res[dt.split("-")[2]-1]==="0")
let weekends = listDate.filter(dt => res[dt.split("-")[2]-1]==="1")
console.log(weekends)
// same code based on index
listDate.forEach((dt,i) => console.log(dt,res[i]))
weekdays = listDate.filter((dt,i) => res[i]==="0")
weekends = listDate.filter((dt,i) => res[i]==="1")
console.log(weekends)

Related

create array of days in Javascript

I need to create an array of results, to create an easy example a reduce my function.
let startDate = new Date("2022-04-05"); // starting date
let endDate = new Date("2022-04-06"); // ending date
let result = await cycleThroughDays(startDate, endDate);
console.log("result", result)
async function cycleThroughDays(startDate, endDate) {
let res = [];
for (let currentDate = startDate; currentDate <= endDate; currentDate.setDate(currentDate.getDate() + 1)) {
console.log(currentDate)
res.push(currentDate);
}
console.log(res)
return res;
}
The output is:
2022-04-05T00:00:00.000Z
2022-04-06T00:00:00.000Z
[ 2022-04-07T00:00:00.000Z, 2022-04-07T00:00:00.000Z ]
result [ 2022-04-07T00:00:00.000Z, 2022-04-07T00:00:00.000Z ]
I expect an array like
result [ 2022-04-05T00:00:00.000Z, 2022-04-06T00:00:00.000Z ]
but I get
result [ 2022-04-07T00:00:00.000Z, 2022-04-07T00:00:00.000Z ]
You need to create a separate variable to hold the current date, and increment that variable within the loop. Try this.
let startDate = new Date("2022-04-05"); // starting date
let endDate = new Date("2022-04-06"); // ending date
let result = await cycleThroughDays(startDate, endDate);
console.log("result", result)
async function cycleThroughDays(startDate, endDate) {
let res = [];
let current = new Date(startDate);
while (current <= endDate) {
console.log(current);
res.push(current);
current.setDate(current.getDate() + 1);
}
console.log(res);
return res;
}

How to map array based on index position

i have one local date Array Called mainDateArray, i used to call APi Calls to some response, From the resonse i get two Arrays Called "Dates" and "RecordCount". This Dates and record Count have same length and recordCount Array Contains values respective to the "Dates" from the server.
later i need to Draw graph based on this two "mainDateArray" and "recordCount"
if dates Array values does not match with mainDateArray i need to append or push 0 to the "recordsCount" Array
To be more clear
mainDateArray = ["05-May-19","06-May-19","07-May-19","08-May-19","09-May-19","10-May-19","11-May-19"];
dates = ["06-May-19","08-May-19","10-May-19"]; // response date
recordsCount = [20,30,10]; // data for the above dates Array from response
My expected output
op = [0,20,0,30,0,10,0];
example:=> ["05-May-19"=0,"06-May-19"=20,"07-May-19"=0,"08-May-19"=30,"09-May-19"=0,"10-May-19"=10,"11-May-19"=10]
i.e when my response date not includes the maindateArray i need to append 0 in recordCount data any hepls would be helpful for me
Using Array​​.map() and Array​​.indexOf()
var mainDateArray = ["05-May-19", "06-May-19", "07-May-19", "08-May-19", "09-May-19", "10-May-19", "11-May-19"]
var dates = ["06-May-19", "08-May-19", "10-May-19"]
var recordsCount = [20, 30, 10]
var result = mainDateArray.map((v, i) => recordsCount[dates.indexOf(v)] || 0)
console.log(result)
You could create a Map of the date -> recordsCount and then Array#map over mainDateArray array, checking if the date exists in the map or not.
const mainDateArray = [
"05-May-19",
"06-May-19",
"07-May-19",
"08-May-19",
"09-May-19",
"10-May-19",
"11-May-19"
];
const dates = ["06-May-19", "08-May-19", "10-May-19"]; // response date
const recordsCount = [20, 30, 10]; // data for the above dates Array from response
const datesMap = new Map(dates.map((date, idx) => [date, recordsCount[idx]]));
const op = mainDateArray.map(date =>
datesMap.has(date) ? datesMap.get(date) : 0
);
console.log(op);
The easiest way IMO is to use an object to keep track of the counts.
// create object for key (i.e. date) based lookup
var counts = {};
for(var i in mainDateArray){
var date = mainDateArray[i];
counts[date] = 0;
}
// update counts
for(var i in dates){
var date = dates[i];
counts[date] += recordsCount[i];
}
// output
var op = [];
for(var i in mainDateArray){
var date = mainDateArray[i];
op.push(counts[date]);
}
Please try this will work ..
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
<script>
var mainDateArray = ["05-May-19","06-May-19","07-May-19","08-May-19","09-May-
19","10-May-19","11-May-19"];
var output = [];
var dates = ["06-May-19","08-May-19","10-May-19"]; // response date
for(var i=0; i<mainDateArray.length; i++)
{
if($.inArray(mainDateArray[i],dates)!=-1)
{
output.push(mainDateArray[i]);
}
else
{
output.push("0");
}
}
alert(output.toString());
</script>
output = [0,06-May-19,0,08-May-19,0,10-May-19,0]
You can try this
mainDateArray = [
"05-May-19",
"06-May-19",
"07-May-19",
"08-May-19",
"09-May-19",
"10-May-19",
"11-May-19"
];
dates = ["06-May-19", "08-May-19", "10-May-19"]; // response date
recordsCount = [20, 30, 10];
op = [];
for (let i = 0; i < dates.length; i++) {
for (let j = 0; j < mainDateArray.length; j++) {
if (dates[i] === mainDateArray[j]) {
op[j] = recordsCount[i];
} else {
if (!op[j]) op[j] = 0;
}
}
}

get previous years in array using momentjs

How can I generate a list of array till today? I can't hardcode [2016,2017,2018], because I have to do it every year.
function (numberOfYearsBack) { // }
Get the current year using getFullYear(), and use Array.from() with a map function to declare and initialize an array with the values you need:
const years = (back) => {
const year = new Date().getFullYear();
return Array.from({length: back}, (v, i) => year - back + i + 1);
}
console.log(years(3));
function years(count, startYear){
const yearList = [];
const year = startYear || new Date().getFullYear();
for(let i = 0; i < count; i+=1 ){
yearList.push(Number(year)-i)
}
return yearList.sort((a,b)=>a-b)
}
console.log(years(10, 2022))

Looping over two columns and copy rows only when items are matching

I have two sheets with the following datasets :
Sheet 1:
05/12/2016 366505 3299193 217374
06/12/2016 345886 3328374 219832
07/12/2016 328152 3348070 221501
08/12/2016 171627 3308919 222948
09/12/2016 338694 3344380 225481
Sheet 2:
05/12/2016 366505 3299193 217374
06/12/2016 345886 3328374 219832
07/12/2016 328152 3348070 221501
08/12/2016 blank blank blank
09/12/2016 blank blank blank
I would like to be able to loop through each column of the sheet 1
then compare with each column of the sheet 2 and for each date missing, I would like to copy the corresponding data in Sheet 2.
I've been able to wrote this until now, but I'm not sure of the logic I should use and how I should organise my code :
function myFunction() {
var sheet1 = SpreadsheetApp.openById("ID").getSheetByName("Sheet1");
var sheet2 = SpreadsheetApp.openById("ID").getSheetByName("Sheet2");
var date1 = sheet1.getRange(2, 1, sheet1.getLastRow()).getValues();
var date2 = sheet2.getRange(2, 1, sheet1.getLastRow()).getValues();
var lastRow = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].getLastRow()
for (var i = 0; i < date1.length; i++){
var list1 = date1[i][0];
var list2 = date2[i][0];
if ( //comparison between list1 and list 2 here ){
var data1 = sheet1.getRange(1,2).getValue();
var data2 = sheet1.getRange(1,3).getValue();
var data3 = sheet1.getRange(1,4).getValue();
sheet2.getRange(i+1, 1,sheet1.getLastRow(), sheet1.getLastColumn()).appendRow([data1,data2,data3]);}
}
edit #1: I rewrite most of my question. It wasn't clear at all. I hope it's better now !
Modified #SimonBreton Code to reduce overhead operation. Details of modification are commented in the code. In short don't use getValue/s and setValue/s repeatedly, better to get all the data/date at once to an array, modify that array. Once all the modification is done set values using the array once at the end.
function myFunction() {
var sheet1 = SpreadsheetApp.openById("ID").getSheetByName("Sheet1");
var sheet2 = SpreadsheetApp.openById("ID").getSheetByName("Sheet2");
//Get all the values as array rather then using getValues repeatedly.
//Note: also gave num of columns as 3, to get values for all three columns/
var date1 = sheet1.getRange(1, 2, sheet1.getLastRow(),3).getValues(); //getRange(row, column, numRows, numColumns)
var date2 = sheet2.getRange(1, 2, sheet1.getLastRow(),3).getValues();
// You can compare and add data to your date2 array
for (var i = 0; i < date1.length; i++){
test = date1[i][0]
if(i < date2.length){ // make sure you dont exceed the length of the second array
test1 = date2[i][0]
if (test != test1 ) {
date2[i] = date1[i] // Note this is pass by reference, so if you modify date1 within this code. date2 will be also be modified.
}
}
else { //if you have more data in date1 use push to add elements to the end
date2.push(date1[i])
}
}
// Write the data only once at the end with the update date2 array.
sheet2.getRange(1,2,date2.length,date2[0].length).setValues(date2)
}
Got a working code here :
function myFunction() {
var sheet1 = SpreadsheetApp.openById("ID").getSheetByName("Sheet1");
var sheet2 = SpreadsheetApp.openById("ID").getSheetByName("Sheet2");
var date1 = sheet1.getRange(1, 2, sheet1.getLastRow()).getValues(); //getRange(row, column, numRows, numColumns)
var date2 = sheet2.getRange(1, 2, sheet1.getLastRow()).getValues();
for (var i = 0; i < date1.length; i++){
test = sheet2.getRange(i+1, 2).getValue()
test1 = sheet1.getRange(i+1, 2).getValue()
if (test != test1 ) {
var data1 = sheet1.getRange(i+1,2).getValue();
var data2 = sheet1.getRange(i+1,3).getValues();
var data3 = sheet1.getRange(i+1,4).getValue();
sheet2.getRange(i+1, 2).setValue(data1);
sheet2.getRange(i+1, 3).setValue(data2);
sheet2.getRange(i+1, 4).setValue(data3);
}
}
}

How to create count object array using date array javascript

My javascript array like that.
var datearray = [
"2016-01-13",
"2016-01-18",
"2016-01-30",
"2016-02-13",
"2016-02-18",
"2016-02-28",
"2016-03-13",
"2016-03-23",
"2016-03-30",
"2016-04-13",
"2016-04-18",
"2016-04-30",
"2016-05-13",
"2016-05-18",
"2016-05-28",
"2016-06-13",
"2016-06-23",
"2016-06-30",
"2016-08-22"
]
but my searching dates are startDate = 2015-12-01; and endDate = 2016-09-30; I want to get new date array between above startDate and endDate. This new array will display like this,
var newOjArray = [
{"2015-12":"0"},
{"2016-01":"3"},
{"2016-02":"3"},
{"2016-03":"3"},
{"2016-04":"3"},
{"2016-05":"3"},
{"2016-06":"3"},
{"2016-07":"0"},
{"2016-08":"1"},
{"2016-09":"0"}
];
values meaning total count of considering date range. How I created It.
A complete proposal. With an array with the wanted grouped result.
function getGroupedData(dates, from, to) {
function pad(s, n) { return s.toString().length < n ? pad('0' + s, n) : s; }
var temp = Object.create(null),
result = [],
fromYear = +from.slice(0, 4),
fromMonth = +from.slice(5, 7),
toYear = +to.slice(0, 4),
toMonth = +to.slice(5, 7),
o, k;
datearray.forEach(function (d) {
var k = d.slice(0, 7);
temp[k] = (temp[k] || 0) + 1;
});
while (true) {
k = pad(fromYear, 4) + '-' + pad(fromMonth, 2);
o = {};
o[k] = (temp[k] || 0).toString();
result.push(o);
if (fromYear === toYear && fromMonth === toMonth) {
break;
}
fromMonth++;
if (fromMonth > 12) {
fromMonth = 1;
fromYear++;
}
}
return result;
}
var datearray = ["2016-01-13", "2016-01-18", "2016-01-30", "2016-02-13", "2016-02-18", "2016-02-28", "2016-03-13", "2016-03-23", "2016-03-30", "2016-04-13", "2016-04-18", "2016-04-30", "2016-05-13", "2016-05-18", "2016-05-28", "2016-06-13", "2016-06-23", "2016-06-30", "2016-08-22"];
console.log(getGroupedData(datearray, '2015-12-01', '2016-09-30'));
You can use Array.filter to filter through this array. Taking advantage of your particular date format, we do not need to do any date arithmetic, we can simply compare dates as strings and use localeCompare() to compare them:
var datearray = [
"2016-01-13",
"2016-01-18",
"2016-01-30",
"2016-02-13",
"2016-02-18",
"2016-02-28",
"2016-03-13",
"2016-03-23",
"2016-03-30",
"2016-04-13",
"2016-04-18",
"2016-04-30",
"2016-05-13",
"2016-05-18",
"2016-05-28",
"2016-06-13",
"2016-06-23",
"2016-06-30",
"2016-08-22"
];
var startDate = "2015-12-01";
var endDate = "2016-01-30";
var filteredArray = datearray.filter(function(item){
return item.localeCompare( startDate ) > -1 && endDate.localeCompare( item ) > -1;
});
console.log( filteredArray );
Now, you have the filteredArray and you can simply iterate through it to count the number of dates falling in a month.
You may try this:
Underscore.js has been used to manipulate data.
var datearray=["2016-01-13","2016-01-18","2016-01-30","2016-02-13","2016-02-18","2016-02-28","2016-03-13","2016-03-23","2016-03-30","2016-04-13","2016-04-18","2016-04-30","2016-05-13","2016-05-18","2016-05-28","2016-06-13","2016-06-23","2016-06-30","2016-08-22"];
var boxingDay = new Date("12/01/2015");
var nextWeek = new Date("09/30/2016");
function getDates( d1, d2 ){
var oneDay = 24*3600*1000;
for (var d=[],ms=d1*1,last=d2*1;ms<last;ms+=oneDay){
var new_Date=new Date(ms);
d.push( new_Date.getFullYear()+"-"+("0" + (new_Date.getMonth() + 1)).slice(-2) );
}
return d;
}
var x=[];
_.each(datearray, function(e){x.push(e.substring(0, 7));});
var z= _.uniq(getDates( boxingDay, nextWeek ));
var f=x.concat(_.uniq(getDates( boxingDay, nextWeek )));
document.getElementById("xx").innerHTML=JSON.stringify(_.countBy(f));
<script src="http://underscorejs.org/underscore-min.js"></script>
<div id="xx"></div>
If you looking for a more ES6 way then check it out:
var dateArray = ["2016-01-13", "2016-01-18", "2016-01-30", "2016-02-13", "2016-02-18", "2016-02-28", "2016-03-13", "2016-03-23", "2016-03-30", "2016-04-13", "2016-04-18", "2016-04-30", "2016-05-13", "2016-05-18", "2016-05-28", "2016-06-13", "2016-06-23", "2016-06-30", "2016-08-22"];
var group = {};
dateArray.forEach(date =>
group[(date = date.substr(0, 7))] =
(group[date] || []).concat(date)
);
var result = Object.keys(group)
.map(date => ({
[date]: group[date].length
}));
console.log(result)
If your date format is as the date array then the easiest way would be to use substr if the length is not constant then you can split it by spacer and then get the two first values. And if it's totally a date string you can create a date from this and convert it to your desired string as key of your object.

Categories

Resources