1

Take the following Javascript Array:

["21587569", "21587570", "21587572", "31856855", "31856854"]

You can visually see that the first 3 items are within a limit of 5 of any other item in that "group", the same can be said for the items at index 3 & 4.

How can I group these "similar" items using Javascript array functions, such as the following output array?

[{"21587569", "21587570", "21587572"},{"31856855", "31856854"}]

The items may not always be presented in order as they are in the example input array.

5
  • Does each number need to be within 5 digits of ANY item in the group, or EVERY item? Commented Jan 26, 2022 at 17:31
  • I believe you are looking for clustering algorithms. You may want to Google for it. Commented Jan 26, 2022 at 17:35
  • @404 - that's a good point. Each item needs to be within 5 of ANY of the other items. Commented Jan 26, 2022 at 17:42
  • please add an exampel for it. what about the order? what if you have 21587575 as well. should it be alone or take a smaller item as well, and how much? Commented Jan 26, 2022 at 17:43
  • @NinaScholz - This data is a subset of a larger set of data and the numbers in question are sequence numbers. Therefore they will always be unique. A real-world example is: 25932906,25932910,25932912,25932995,25932996,25933013,25933014 These sequence numbers all occurred within the same millisecond of this smaller dataset and therefore. Items with grouped or almost grouped sequence numbers are likely to be related (nanosecond timing is not available in this dataset). Commented Jan 26, 2022 at 17:52

1 Answer 1

1

You could sort and get groups if the delta of last items is smaller than five.

const
    data = [21587569, 21587570, 21587572, 31856855, 31856854],
    result = [...data]
        .sort((a, b) => a - b)
        .reduce((r, v) => {
            const last = r[r.length - 1];
            if (!last || v - last[last.length - 1] > 5) r.push([v]);
            else last.push(v);
            return r;
        }, []);

console.log(result);
    

Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what I was looking for, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.