Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

javascript - Group array elements depending on their value

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

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

1 Reply

0 votes
by (71.8m points)

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; }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...