2017-03-02 3 views
-1

Ich brauche Ihre Hilfe mit diesem Array, ich weiß wirklich nicht, wie dies zu sortieren:Komplizierte Array Gruppierung

[{userId: "3t5bsFB4PJmA3oTnm", from: 1, to: 6}, 
{userId: "3t5bsFB4PJmA3oTnm", from: 7, to: 15}, 
{userId: "3t5bsFB4PJmA3oTnm", from: 172, to: 181}, 
{userId: "3t5bsFB4PJmA3oTnm", from: 182, to: 190}] 

in das:

[{userId: "3t5bsFB4PJmA3oTnm", from: 1, to: 15}, 
{userId: "3t5bsFB4PJmA3oTnm", from: 172, to: 190}] 

Können Sie mir helfen? Es kann lodash oder Unterstreichung sein, ich versuchte mit beiden und wirklich kann dieses Problem nicht lösen

+0

, die nicht wie Sortierung mir sieht. Sieht so aus, als würde man Gegenstände kombinieren. – epascarello

+1

Es ist nicht das Sortieren, das Sie möchten. Außerdem; Unter welcher Bedingung gruppieren Sie die Von/Bis-Felder, da die Benutzer-ID für alle gleich ist. –

+0

sind deine Werte nicht überlappend und in Ordnung? –

Antwort

0

Sie konnten das userId überprüfen und wenn das selbe, die Prüfung, wenn die Einzelteile in der Ordnung sind, dann Änderung to Eigenschaft.

Es funktioniert für sortierte Elemente. Wenn nicht sortiert, können Sie vorher eine Sortierung vornehmen.

data.sort(function (a, b) { 
    return a.userId.localeCompare(b.userId) || a.from - b.from; 
}); 

var data = [{ userId: "3t5bsFB4PJmA3oTnm", from: 1, to: 6}, { userId: "3t5bsFB4PJmA3oTnm", from: 7, to: 15 }, { userId: "3t5bsFB4PJmA3oTnm", from: 172, to: 181 }, { userId: "3t5bsFB4PJmA3oTnm", from: 182, to: 190 }], 
 
    result = data.reduce(function (r, a) { 
 
     var last = r[r.length - 1] || {}; 
 
     if (last.userId === a.userId && last.to + 1 === a.from) { 
 
      last.to = a.to; 
 
     } else { 
 
      r.push({ userId: a.userId, from: a.from, to: a.to }); 
 
     } 
 
     return r; 
 
    }, []); 
 

 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }