3

I have string like this

    '10:00','13:00','12:00','15:00','08:00','12:00'

I need it in format like this

Array(3)

  Array[0] ['10:00', '13:00']
  Array[1] ['12:00', '15:00']
  Array[2] ['08:00', '12:00']

I tried with split method but without success.

user3590094
  • 119
  • 1
  • 2
  • 11
  • 2
    "I tried with split method but without success." Please show your code. – str Aug 31 '18 at 07:38
  • This might be helpful https://gist.github.com/webinista/11240585 – kgbph Aug 31 '18 at 07:39
  • @kgbph You should *never* extend the prototypes of built-ins. E.g. never extend `Array.prototype`. – str Aug 31 '18 at 07:40
  • @str Why not? It's perfectly fine to extend prototypes if well documented. And of course you need to take care of conflicts. But if someone extends prototypes he/she should know what they do anyway. – Akaino Aug 31 '18 at 07:43
  • @Akaino [Why is extending native objects a bad practice?](https://stackoverflow.com/questions/14034180/why-is-extending-native-objects-a-bad-practice) – str Aug 31 '18 at 07:48
  • @str I know that. But it also states `Changing the behaviour of an object that will only be used by your own code is fine.` So I still don't see a problem if you know what you're doing. Not saying it's good practice. – Akaino Aug 31 '18 at 07:58
  • @Akaino The problem is that not many people know what it implies and how it can break their code. And there are many cases where it even influenced the development of ECMAScript in a bad way. For example, `Array.prototype.includes` is called `includes` because `contains` was already used by many libraries and the committee feared the incompatibilities. – str Aug 31 '18 at 08:37

7 Answers7

6

You could replace single quotes with double quotes, add brackes and parse it as JSON and get an array, which is the grouped by two elements.

var string = "'10:00','13:00','12:00','15:00','08:00','12:00'",
    array = JSON
        .parse('[' + string.replace(/'/g, '"') + ']')
        .reduce((r, s, i) => r.concat([i % 2 ? r.pop().concat(s) : [s]]), []);

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
5

var str = "'10:00','13:00','12:00','15:00','08:00','12:00'";
var oldArray = str.split(',');
var newArray = [];

while(oldArray.length){
    let start = 0;
    let end = 2;
    newArray.push(oldArray.slice(start, end));
    oldArray.splice(start, end);
 }
 
 console.log(newArray);
Harun Or Rashid
  • 5,589
  • 1
  • 19
  • 21
1

You can use String.split(',') to split into individual values, then group them based on their positions (result of integer division with 2).

I am using groupBy from 30 seconds of code (disclaimer: I am one of the maintainers of the project/website) to group the elements based on the integer division with 2. Short explanation:

Use Array.map() to map the values of an array to a function or property name. Use Array.reduce() to create an object, where the keys are produced from the mapped results.

The result is an object, but can be easily converted into an array using Object.values() as shown below:

var data = "'10:00','13:00','12:00','15:00','08:00','12:00'";

const groupBy = (arr, fn) =>
  arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => {
    acc[val] = (acc[val] || []).concat(arr[i]);
    return acc;
  }, {});

var arr = data.split(',');
arr = groupBy(arr, (v, i) => Math.floor(i / 2));
arr = Object.values(arr);

console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Angelos Chalaris
  • 6,611
  • 8
  • 49
  • 75
1

How about:

"'10:00','13:00','12:00','15:00','08:00','12:00'"
.replace(/'/g, '').replace(/(,[^,]*),/g,"$1;")
.split(';').map(itm => itm.split(','))
Stefan Blamberg
  • 816
  • 9
  • 24
1

In this case you want to compare 2 values. To do this you can make a for loop that reads the current value and the last value and compares the two. If the last value is higher than current value, the splitting logic happens.

Either you add the current value to the last item (which is an array of strings) in the results array or you add a new array of strings at the end of the results array.

Webber
  • 4,672
  • 4
  • 29
  • 38
1

One potential solution:

let S = "'10:00','13:00','12:00','15:00','08:00','12:00'";

let R = S.split(',');

let I = 0;

let A = new Array([],[],[]);

R.map((object, index) => {
    A[I][index % 2] = R[index];
    if (index % 2 == 1) I++;
});

console.log(A);
InfiniteStack
  • 430
  • 2
  • 9
0

I think use JSON.parse is better:

var array = "'10:00','13:00','12:00','15:00','08:00','12:00'";

array = JSON.parse( '[' + array.replace(/'/g,'"') + ']' );

var array2 = [];
for(var i=0;i < array.length - 1; i++){
    array2.push([array[i], array[i+1]]);
}

console.log(array2);
morteza ataiy
  • 541
  • 4
  • 12