1

I am trying to pass an array to a function and convert the numeric date.

E.g.: 2020-02-29 converted to 29th February 2020 (Saturday).

My code is below. When I am trying to push the converted date to array, the previous value get overwritten. I have gone through many articles on StackOverflow, but didn't find any best solution for it. I have created a new local array before pushing the same one (the same reference) each time, but the problem still persist.

Could you suggest me a better solution for my problem statement OR should I do some modification in the existing code?

Array data as input:

var data = ['2020-02-29', '2020-03-01', '2020-03-02'];

Start of a function:

function getFullName(data) {
    for(var i=0;i<data.length;i++){
        var d = new Date(data[i]);
        var date = d.getDate();
        var month = d.getMonth();
        var year = d.getFullYear();
        var dayName = d.toLocaleDateString('en-US', { weekday: 'long' });

        function ordinal_suffix_of(i) {
            var j = (i % 10);
            k = (i % 100);
            if (j == 1 && k != 11) {
                return i + "st";
            }
            if (j == 2 && k != 12) {
                return i + "nd";
            }
            if (j == 3 && k != 13) {
                return i + "rd";
            }
            return i + "th";
        }
        var pdate = ordinal_suffix_of(date);

        var monthNames = ["January", "February", "March", "April", "May", "June",
            "July", "August", "September", "October", "November", "December"
        ];
        var result = [];
        var pmonth = monthNames[month];
        var response = pdate + ' ' + pmonth + ' ' + year + ' (' + dayName + ')';
        result.push(response);
        console.log(result);
    }
     return result;
};

Calling function:

getFullName(data);
1
  • It is not the push who overwrites your data but it is response = because you store the variable response in your result array and you change the variable value also you write result = [] everytime you call the function which resets result Commented Mar 26, 2020 at 17:43

3 Answers 3

1

There is just a minor issue with the code, your result variable must be defined outside the loop:

// Array data as input

var data = ['2020-02-29', '2020-03-01', '2020-03-02'];

// Start of a function

function getFullName(data) {
    var result = []; // Define here
    for(var i=0;i<data.length;i++){
        var d = new Date(data[i]);
        var date = d.getDate();
        var month = d.getMonth();
        var year = d.getFullYear();
        var dayName = d.toLocaleDateString('en-US', { weekday: 'long' });

        function ordinal_suffix_of(i) {
            var j = (i % 10);
            k = (i % 100);
            if (j == 1 && k != 11) {
                return i + "st";
            }
            if (j == 2 && k != 12) {
                return i + "nd";
            }
            if (j == 3 && k != 13) {
                return i + "rd";
            }
            return i + "th";
        }
        var pdate = ordinal_suffix_of(date);

        var monthNames = ["January", "February", "March", "April", "May", "June",
            "July", "August", "September", "October", "November", "December"
        ];
        var pmonth = monthNames[month];
        var response = pdate + ' ' + pmonth + ' ' + year + ' (' + dayName + ')';
        result.push(response);
    }
     return result;
};

// Calling function 

console.log(getFullName(data));

Sign up to request clarification or add additional context in comments.

Comments

0

Move your var result = []; declaration before for loop, because result is overwritten in every iteration

function broken() {
  for( var i = 0; i < 3; i++ ) {
    var result = [];
    result.push(i)
  }
  return result;
}

function fixed() {
  var result = [];
  for( var i = 0; i < 3; i++ ) {  
    result.push(i)
  }
  return result;
}


console.log(broken());
console.log(fixed());

Comments

0

Because you are initializing your var result = [] within the for(...){}, your result gets "wiped out" and creates a new array every iteration of your for loop

you can solve the problem by moving var result = [] to the outside of your getFullName function OR move it outside of for loop

p.s. This looks like you need to understand more about what lexical scope is in javascript. I suggest doing some research into the high-level concept of lexical scopes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.