ข้อมูลตัวอย่าง
var listOfStrings = ["10.45322,-6.8766363", "78.93664664,-9.74646646", "7888.7664664,-10.64664632"];
วิธีทำ
ใช้ split(',') แยกค่า แล้ว map(Number) แปลงเป็นตัวเลข แยกเก็บ latitude (บวก) และ longitude (ลบ)
ตัวอย่างโค้ด
var listOfStrings = ["10.45322,-6.8766363", "78.93664664,-9.74646646", "7888.7664664,-10.64664632"];
var latitude = [];
var longitude = [];
listOfStrings.forEach(obj => obj.split(',')
.map(Number)
.forEach((value, index) => [latitude, longitude][index].push(value))
);
console.log("All positive value is latitude=")
console.log(latitude);
console.log("All negative value is longitude=")
console.log(longitude);
วิธีรัน
node fileName.js
ชื่อไฟล์ demo180.js
ผลลัพธ์
PS C:\Users\Amit\javascript-code> node demo180.js All positive value is latitude= [ 10.45322, 78.93664664, 7888.7664664 ] All negative value is longitude= [ -6.8766363, -9.74646646, -10.64664632 ]
คำอธิบาย
forEach วนลูปแต่ละ string split(',') แยก lat,long map(Number) แปลง string เป็น number forEach นested ใช้ index (0=lat, 1=long) push เข้า array ที่เหมาะสม