Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have this array of objects:

[
  { name: 'foo1', speed: 8 },
  { name: 'foo2', speed: 7 },
  { name: 'foo3', speed: 10 },
  { name: 'foo4', speed: 12 },
  { name: 'foo5', speed: 8 },
  { name: 'foo6', speed: 5 }
]

Now I'd like to group the elements of array into chunk based on the "speed" property. If the speed of the current, next and previous elements are <= 10 then the elements should be grouped together. If happens otherwise then another group is created which collects the elements which have speed property >10.

In the end I'd like to have an array of 3 arrays like this:

[
  [
    { name: 'foo1', speed: 8 },
    { name: 'foo2', speed: 7 },
    { name: 'foo3', speed: 10 }
  ], [
    { name: 'foo4', speed: 12 }
  ], [
    { name: 'foo5', speed: 8 },
    { name: 'foo6', speed: 5 }
  ]
]

It is important to keep the order of elements, just make them grouped. The length of base array can vary so everything must be dynamically calculated. I've tried to use some loadash methods however I got stuck with no real solution.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
321 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you want to group by a threshold, you should use > rather than >=.

Just reduce the items, and use an exclusive-or logic check.

const data = [
  { name: 'foo1', speed: 8 },
  { name: 'foo2', speed: 7 },
  { name: 'foo3', speed: 10 },
  { name: 'foo4', speed: 12 },
  { name: 'foo5', speed: 8 },
  { name: 'foo6', speed: 5 }
];

const groupDataByThreshold = ([ head, ...rest ], key, threshold) =>
  rest.reduce((result, item) => {
    const prevGroup = result[result.length - 1],
          prevItem = prevGroup[prevGroup.length - 1],
          prevOver = prevItem[key] > threshold,
          currOver = item[key] > threshold;
    if ((currOver && prevOver) || (!currOver && !prevOver)) {
      prevGroup.push(item);
    } else {
      result.push([ item ]);
    }
    return result;
  }, [ [ head ] ])

const grouped = groupDataByThreshold(data, 'speed', 10);

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...