Cara mengelompokkan dan Memisahkan objek array yang berasal dari server. susunan seperti ini: (MOVINGSTATE s Ini berarti Berhenti danm bergerak. XPOINT dan YPOINT Ini berarti garis lintang dan garis bujur mobil.)

[{MOVINGSTATE: "s",XPOINT:53.9172866,YPOINT: 26.518275},
{MOVINGSTATE: "s",XPOINT: 53.9172866,YPOINT: 26.518275},
{MOVINGSTATE: "m",XPOINT: 54.0215383,YPOINT: 26.5275599},
{MOVINGSTATE: "m",XPOINT: 54.0102666,YPOINT: 26.4989583},
{MOVINGSTATE: "s",XPOINT: 54.0016599,YPOINT: 26.5478316},..]

Saya ingin jika beberapa MOVINGSTATE Continuous s goto new array dan ketika MOVINGSTATE berubah menjadi mgoto new array dan lagi MOVINGSTATEmengubah ke s masuk ke array baru. semua objek array baru ini dari array utama lainnya. saya menggunakan loadash

var aaa = _loadash.groupBy(props,'MOVINGSTATE')

Tapi Keluarkan ini:

{m:Array(2),s:Array(3)}

Saya ingin output seperti ini:

[
 [
  {MOVINGSTATE: "s",XPOINT:53.9172866,YPOINT: 26.518275},
  {MOVINGSTATE: "s",XPOINT: 53.9172866,YPOINT: 26.518275}
  ],
 [
  {MOVINGSTATE: "m",XPOINT: 54.0215383,YPOINT: 26.5275599},
  {MOVINGSTATE: "m",XPOINT: 54.0102666,YPOINT: 26.4989583}
 ],
 [
  {MOVINGSTATE: "s",XPOINT: 54.0016599,YPOINT: 26.5478316}
 ]
]

Bagaimana ini terima kasih telah membantu

0
Amir Farahani 1 Juli 2020, 17:07

1 menjawab

Jawaban Terbaik

Coba ini:

let arr = 
[{MOVINGSTATE: "s",XPOINT:53.9172866,YPOINT: 26.518275},
{MOVINGSTATE: "s",XPOINT: 53.9172866,YPOINT: 26.518275},
{MOVINGSTATE: "m",XPOINT: 54.0215383,YPOINT: 26.5275599},
{MOVINGSTATE: "m",XPOINT: 54.0102666,YPOINT: 26.4989583},
{MOVINGSTATE: "s",XPOINT: 54.0016599,YPOINT: 26.5478316}];

  let result =  arr.reduce( (accumulator, cur) => {
    const key = cur["MOVINGSTATE"];
    const keyExists = accumulator.find(obj => obj.key === key);
    if (!keyExists) {
      accumulator.push({key,value:[cur]});
      return accumulator;      
    } else if(accumulator[accumulator.length -1] && accumulator[accumulator.length -1].key === key){
        accumulator[accumulator.length -1].value.push(cur);
        return accumulator;
    } else {
      accumulator.push({key,value:[cur]});
      return accumulator; 
    }
        
  }, [])
  .map(obj => obj.value)
1
Ravi Kukreja 1 Juli 2020, 15:00