I need to group the points of a <polyline>
into an array of [x, y]
coordinates. Usually SVGPolylineElement
items validate with both comma separated values AND space only separated values.
var points = "0 0 50 0 25 50 0 0".split(/s|,/); // or points="0,0 50,0 25,50 0,0" // how to group the points like this points = [[0,0], [50,0], [25,50], [0,0]];
I’m working around:
points = [].concat(points.slice().map((v,i) => { // what to do here? // I know I need to make use of i%2 === 0 // I don't know how to break the original array }))
I need an ES6 solution to group arrays like shown above.
Advertisement
Answer
const str = "0 0 50 0 25 50 0 0".split(/s|,/).map(Number) const res = [] let curr = 0 while(curr < str.length) { res.push([str[curr], str[curr + 1]]) curr += 2 } console.log(res)