Check array elements has value - javascript

For example I have code like this:
var myArr="14:44:45".split(":");
But sometimes time value doesn't have "seconds" information.
var myArr="14:44".split(":");
Basicly sometimes the string has value of "seconds" and sometimes has not.So how can I check if the myArr[2] has value.What is the best practice for that?
if(myArr.length === 3)
Is it okay?
Edit: or
if(myArr[2])

Your approach is correct
A better approach is destructuring the array and checking for the variable seconds
let [h, m, s] = "14:44:45".split(":");
if (s) console.log('Has seconds');
let [hh, mm, ss] = "14:44".split(":");
if (!ss) console.log("Doesn't have seconds");
Resource
Destructuring assignment

As others have said, your approach is almost fine. You might want to check that the length is greater than 2 rather than equal to 3, but that might never be an issue.
But I have an alternate suggestion:
const timeParts = time => {
const [hours, minutes = 0, seconds = 0] = time.split(':').map(Number)
return {hours, minutes, seconds}
}
console.log(timeParts('14:44:45')) //=> {hours: 14, minutes: 44, seconds: 45}
console.log(timeParts('14:45')) //=> {hours: 14, minutes: 45, seconds: 0}
Rather than doing an explicit check this simply gives default values for the minutes and seconds. If you don't want the numeric conversion replace the first line of the function with
const [hours, minutes = '00', seconds = '00'] = time.split(':')

Example 1 uses split() and .length` and a ternary operator to compare length of array. If you only have one or two timestamps this is sufficient.
Example 2 uses .map() to iterate through an array of timestamps. Each timestamp is compared by the same function from the the previous example. If you have more than one timestamp to check try this example.
Example 3 is like the previous example and it will append :00 to any timestamp that needs it. If you have more than one timestamp and actually want to fix them as well try this example.
Demo
//~~~~~~~~~~~~If you have one or two timestamps~~~~~~~~~~~~~Example 1
function sec(stamp) {
return stamp.split(':').length < 3 ? 'No Seconds':'Has Seconds';
}
let r0 = sec("14:44:45");
let r1 = sec("14:44");
console.log(r0);
console.log(r1);
//~~~~~~~~~~~~If you have more than one timestamp~~~~~~~~~~~~Example 2
const times = ["14:44:45", "14:44", "20:59:10", "7:23:32", "3:04", "15:46", "8:18"];
const secChk = times.map(function(time) {
return time.split(':').length < 3 ? 'No Seconds':'Has Seconds';
});
console.log(secChk);
//~~~~~If you have more than one timestamp you want to fix~~~~Example 3
const secFix = times.map(function(time, index) {
return time.split(':').length < 3 ? '['+index+']: '+time+':00 - Fixed':'['+index+']: '+time;
});
console.log(secFix);

Related

Slice method indexing issue in Javascript

I have a string as an input in the form; lets say "1,5;6,10". Now, I want to compare the number at position 1 and 3 .i.e.(1 & 6). Whichever one is largest the number right to it would be printed. In this case the number 10 would be printed as 1 < 6.
Let the input is,
const customer_demand ="1,5;6,10";
I want to procced with slice() method and separate 1 and 6 with:
const number1 = customer_demand.slice(0, 1); // 1
const number2 = customer_demand.slice(4, 5); // 6
and compare the resultants with if & else. But there may be a case when the third number is two digit like:
const customer_demand ="1,5;16,10";
my slice() method index would go offset. What can I do in this regard? I hope I have made myself clear, if not please leave a comment. Thanks
In your case it's better to use split:
const customer_demand ="1,5;16,10";
const number1 = customer_demand.split(";")[0].split(",")[0]; // 1
const number2 = customer_demand.split(";")[1].split(",")[0]; // 16
Also if you want them to be Numbers don't forget to cast it using parseInt.
The solution, use split. Here's an example
const customer_demand ="1,5;16,10";
function parseNumbers(string){
return string.split(";") //returns stuff like ["1,5", "16,10"]
.map(axis=>
axis.split(",") //["1", "5"]
.map(n=>parseInt(n)) //[1,5]
)
}
//example usage
const parsedDemand=parseNumbers(customer_demand)
const [number1,number2,number3,number4]=parsedDemand
console.log(parsedDemand)
Make your life easier and break up your strings into managable arrays. Here is an example of when you don't know how many sets of numbers to compare ahead of time.
const customer_demand ="1,5;16,10";
// the following should also work for data like: "1,3,4,7;1,44;100"
let answers = [];
customer_demand.split(";").forEach( set => {
let setitems = set.split(",");
let biggest = setitems.reduce(function(a, b) {
return Math.max(Number(a), Number(b));
});
answers.push(biggest)
});
// answers is now an array - each item is the biggest number of that set. In your example it would be [5,16]

Change Time format

I have a time string and I want to convert it to have : between the hour and minutes. Any suggestions on how to take the sting and change it. I’m assuming I need to use regular expression but not sure how to format that code. Any suggestions would be great.
var number = '1340';
moment(number).format('hh:mm')
console.log(number)
// The output I want would be 13:40
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
Stick a : before the last 2 digits. This makes the assumption that your minutes are padded with zeroes if not 2 digits long:
console.log('1340'.replace(/\d{2}$/, m => ':' + m));
First off, in the code you show you are outputing the original string not the result from moment.js.
If you want to use moment, you'll need to tell it what format your string is:
var number = '1340';
var time = moment(number, 'hhmm').format('hh:mm')
console.log(time)
var number = '1340';
console.log(number.slice(0, 2)+":"+number.slice(2));
const number = "1340";
const time = `${number.substring(0,2)}:${number.substring(2,4)}`;
console.log(time);
Moment needs a date.
You want something like this
const pad = num => ("00"+num).slice(-2);
const hhmm = str => {
const mm = str.slice(-2)
const hh = str.slice(0,-2)
return `${pad(hh)}:${pad(mm)}`;
};
console.log(hhmm('1340'))
console.log(hhmm('340'))
console.log(hhmm('40'))
console.log(hhmm('0'))
console.log(hhmm(''))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>

Get the difference between two variables

I have an object and Hours is saved as a string . I need to convert the string to hours and then get the difference between the 2 variables.
const groupSchedule=[
{"days":"sat","Hourfrom":"15:00","Hourto":"19:00"},
{"days":"sun","Hourfrom":"15:00","Hourto":"19:00"},
{"days":"mon","Hourfrom":"15:00","Hourto":"19:00"},
]
function numberOfHoursInWeek(groupSchedule) {
let hours = 0;
for (const gSchedule of groupSchedule) {
let hour = gSchedule.Hourto.to - gSchedule.Hourfrom;
console.log(hour);
hours += hour;
}
return hours;
}
Problem in converting string to hour (NAN)
I tried to write in a very verbose way. You could do something like this:
const hoursTo = "19:33";
const hoursFrom = "14:55";
const hoursToArray = hoursTo.split(":");
const hoursFromArray = hoursFrom.split(":");
const hoursToDate = new Date(0, 0, 0, hoursToArray[0], hoursToArray[1], 0, 0);
const hoursFromDate = new Date(0, 0, 0, hoursFromArray[0], hoursFromArray[1], 0, 0);
const difference = Math.abs(hoursToDate - hoursFromDate) / 36e5;
console.log(hours) //4.633333333333334;
The basic issue is that you are taking gSchedule.hourTo and gSchedule.hourFrom and trying to perform arithmetic with them when they are string values. You need to split the string and extract a numeric type to perform this type of mathematical calculation.
In this case the relevant numeric portion is the hours portion of the HH:MMstring, so using the split function with : as a delimiter will return a list of two string, one string of hours and one of minutes. We can then parse the hours string to get an int, float, or other numeric type.
//split time strings on the ':'
let hrToSplit = gSchedule.hourTo.split(':')
let hrFromSplit = gSchedule.hourFrom.split(':')
//parse time strings to extract hour as int
let hrToNum = parseInt(hrToSplit[0], 10)
let hrFromNum = parseInt(hrFromSplit[0], 10)
//perform whatever math is needing using the numbers themselves, not the strings
console.log(hrToNum + hrFromNum)
If you want to do some further reading on different approaches beyond the answers you got here, this is a similar question that may be useful to reference.

Add 0 before single digit number of time format [duplicate]

This question already has answers here:
Adding "0" if clock have one digit
(9 answers)
Closed 3 years ago.
How can we add 0 before single digit number of time format.
Like if I have a time "0:3:25" (hh:mm:ss) format to convert into "00:03:25"
You shouldn't overcomplicate this:
const time = "0:3:25";
const paddedTime = time.split(':').map(e => `0${e}`.slice(-2)).join(':')
console.log(paddedTime)
split the string by semicolons (:), that yields an array (hours, minutes, seconds). map this array with a function that adds a 0 before every item in the array, and slice the last two digits (you get an array again). Then join the resulting array by semicolons (and you get a string).
Or you could use a regex instead of the split:
const time = "0:3:25";
const paddedTime = time.match(/\d+/g).map(e => `0${e}`.slice(-2)).join(':')
console.log(paddedTime)
The last part is the same with regex (map, slice, join).
And you also could use the padStart() (JavaScript built-in function):
const time = "0:3:25";
const paddedTime = time.split(':').map(e => e.padStart(2, 0)).join(':')
console.log(paddedTime)
padStart() on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
You can do something like below (Explanations included):
const time = '0:3:25';
const correctedTime = parseTime(time);
console.log(correctedTime);
function parseTime(time){
return time
.split(':') // Split them into array as chunk of [hour, minute, second]
.map(pad) // Map them with `pad` function below
.join(':'); // Join them back into 'hh:mm:ss'
}
function pad(n){
return parseInt(n) < 10 // If number less than 10
? '0' + n // Add '0' in front
: n; // Else, return the original string.
}
you can add split the existing time string on the ":", then for each portion, add the "0" then take the last two characters. Then simply join the portions back into a striung.
let time = "0:3:25";
function updateTime(){
let newTimePortions = [];
let timePortions = time.split(":");
timePortions.forEach(function(portion,index) {
newTimePortions[index] = ("0" + portion).slice(-2)
})
return newTimePortions.join(':')
}
console.log(updateTime()); // gives 00:03:25
Please try below code
var dateinfo="0:3:25";
var newdate=dateinfo.split(":");
var hdate=newdate[0];
var mdate=newdate[1];
var sdate=newdate[2];
if(hdate.length == 1 ){
hdate="0"+hdate;
}
if(mdate.length == 1 ){
mdate="0"+mdate;
}
if(sdate.length == 1 ){
sdate="0"+sdate;
}
dateinfo=hdate+":"+mdate+":"+sdate;
This is work for me

Select word between two words

How can I create a function that selects everything between the words X and Y and pushes it to an array.
By Greili - 4 Hours and 40 Minutes ago.
#NsShinyGiveaway
0 comments
By ToneBob - 4 Hours and 49 Minutes ago.
#NsShinyGiveaway
0 comments
By hela222 - 5 Hours and 14 Minutes ago.
#NsShinyGiveaway
sure why not? XD
0 comments
By NovaSplitz - 5 Hours and 45 Minutes ago.
#NsShinyGiveaway Enjoy life off PokeHeroes buddy.
0 comments
Given the text above, I want to push each word after "By" and before SPACE onto an array. The result must be something like this:
name[0] = "Greili"
name[1] = "ToneBob"
name[2] = "hela222"
Here's a quick split and reduce:
var arr = str.split("By ").reduce(function(acc, curr) {
curr && acc.push(curr.split(" ")[0]); return acc;
}, []);
Result:
["Greili", "ToneBob", "hela222", "NovaSplitz"]
Demo: JSFiddle
Try using a regular expression:
var regex = /By ([^\s]+)\s/g;
var s = 'string to search goes here';
var names = [];
var result;
do {
result = regex.exec(s);
if (result) {
names.push(result[1]);
}
} while (result);
JSFiddle Example
I see the word you want is always the second word, so that's an easier way of solving the problem. You could split the string on each space, and then you have an array of words, where the word at index 1 is the name you want. Then add each name to a new array.
var words = "By Greili ...".split(" ");
var name = words[1]; // "Greili"
var namesArray = [];
namesArray.push(name);
You'd need to do that for each of your comment strings, in a loop.

Categories

Resources