1

In the code below all I'm trying to do at the moment is split the time variables (time11 and time12) into the hour and minutes value and push those values into an array (array1 for time11 hours & minutes and array 2 for time12 hours & minutes). The problem I'm having is when I print the arrays to the console they are displayed as [["17", "50"]] and [["04", "34"]] where I'd ideally like them to printed like ["17", "50"] & ["04", "34"]. Does anyone know why it's producing 2 sets of square brackets and how to get rid of the outer set. All help is appreciated.

Thanks

var time11 = "17:50";
var time12 = "04:34";

array1 = [];
array2 = [];

var timeDifference = function(time1, time2){
    array1.push(time1.split(/[^\d]/));
    array2.push(time2.split(/[^\d]/));
    console.log(array1);
    console.log(array2);
};

timeDifference(time11, time12);
3
  • 2
    split returns an array, and then you put that into the array1/array2 arrays? What else would you expect? Commented May 4, 2016 at 13:17
  • Try calling timeDifference twice with some values. Commented May 4, 2016 at 13:18
  • 1
    To get what you want you could just write: array1 = time1.split(/[^\d]/)'; Commented May 4, 2016 at 13:18

1 Answer 1

2

push adds an element to an array, and split returns an array. You're therefore adding an array as an element to an array; both of your arrays have one element, which is an array.

The method you're looking for, is concat which will concatenate 2 arrays. But since you're starting from an empty array, you might as well just assign the output of split to the array:

array1 = time1.split(/[^\d]/);
Sign up to request clarification or add additional context in comments.

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.