Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

143
Views
Array.indexOf() return confusing results JavaScript

So I am trying to return a number for what week day it is given a string like 'tue'. So i figured I would get the index of the string 'tue' in an array that contains the week days

week_days = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];

var date = new Date();

var first_month_day = String(new Date(date.getFullYear(), date.getMonth(), 1).toString().slice(0, 4).toLowerCase());

var indexOf = week_days.indexOf(first_month_day)
return indexOf;

first_month_day = 'tue' as of today when I evaluate that code. therfore I would assume that running

week_day.indexOf(first_month_day)

would return 2 but instead i get -1. So if instead of running the above if i do

week_days.indexOf('tue')

I get the desired 2 I have ensured that first_month_day is a string using typeof and everything I am just at a loss as to why it keeps returning -1 whenever I know it exists inside the array.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

As Robin Zigmond said, .slice(0, 4) will give a string with a length of 4, so you were getting "tue " from firstMonthDay instead of "tue".

const weekDays = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];

const date = new Date();

const firstMonthDay = String(new Date(date.getFullYear(), date.getMonth(), 1).toString().slice(0, 3).toLowerCase());

const index = weekDays.indexOf(firstMonthDay);
console.log(index);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!