Steffen Bauer
Steffen Bauer

Reputation: 145

count a specific element in a array

I tried to make a script that takes a row form a sheet full with dates, convert it into an array and count a specific date.

I managed to do all except the "count a specific date" part.

the dates in the array looks like this:

Fri Jan 27 2017 00:00:00 GMT+0100 (MEZ)

The arry:

Fri Jan 27 2017 00:00:00 GMT+0100 (MEZ),Wed Jan 11 2017 00:00:00 GMT+0100 (MEZ),Wed Jan 11 2017 00:00:00 GMT+0100 (MEZ),Wed Jan 11 2017 00:00:00 GMT+0100 (MEZ),Mon Jan 02 2017 00:00:00 GMT+0100 (MEZ),,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

The wanted Output: (for "Wed Jan 11 2017 00:00:00 GMT+0100 (MEZ)"

3

Upvotes: 0

Views: 85

Answers (2)

If you have an array of strings like these:

var arr = ["Fri Jan 27 2017 00:00:00 GMT+0100 (MEZ)", 
           "Wed Jan 11 2017 00:00:00 GMT+0100 (MEZ)", 
           "Wed Jan 11 2017 00:00:00 GMT+0100 (MEZ)", 
           "Wed Jan 11 2017 00:00:00 GMT+0100 (MEZ)", 
           "Mon Jan 02 2017 00:00:00 GMT+0100 (MEZ)"];`

Use 2 strings of code;

var day = new Date(arr[0]);
day = day.getDay() + 1;

Just read docs of Date object:

Date object itself: http://www.w3schools.com/jsref/jsref_obj_date.asp

Date.getDay() method: http://www.w3schools.com/jsref/jsref_getday.asp

Upvotes: 0

ibrahim mahrir
ibrahim mahrir

Reputation: 31692

var array = ["Fri Jan 27 2017 00:00:00 GMT+0100 (MEZ)", "Wed Jan 11 2017 00:00:00 GMT+0100 (MEZ)", "Wed Jan 11 2017 00:00:00 GMT+0100 (MEZ)", "Wed Jan 11 2017 00:00:00 GMT+0100 (MEZ)", "Mon Jan 02 2017 00:00:00 GMT+0100 (MEZ)"];

var dateToCount = "Wed Jan 11 2017 00:00:00 GMT+0100 (MEZ)";

var count = array.reduce(function (a, d) {
    return d == dateToCount ? ++a : a;
}, 0);

console.log(count);

Note: If you could have lowercases or other form of dates and want to get those counted as well, then parse the dates like this:

var dateToCount = Date.parse("Wed Jan 11 2017 00:00:00 GMT+0100 (MEZ)");
var count = array.reduce(function (a, d) {
    return Date.parse(d) == dateToCount ? ++a : a;
}, 0);

Upvotes: 1

Related Questions