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
180 views
in Technique[技术] by (71.8m points)

Array algorithm: How to reform this nested array use javascript?

I have a table like this:

enter image description here

The colored blocks have coordinates as an array:

[
  [1, 1],
  [2, 1],
  [2, 4],
  [2, 5],
  [3, 2],
  [3, 4],
  [4, 4],
  [4, 5],
  [4, 6],
  [4, 7],
  [5, 3],
  [6, 3],
  [6, 4],
  [6, 5]
]

Now I want to group the neighboring blocks (horizontal and vertical) to independent child array.

The output estimated is like:

[
  [
    [1, 1],
    [2, 1]
  ],
  [
    [2, 4],
    [2, 5],
    [3, 4],
    [4, 4],
    [4, 5],
    [4, 6],
    [4, 7]
  ],
  [
    [3, 2]
  ],
  [
    [5, 3],
    [6, 3],
    [6, 4],
    [6, 5]
  ]
]

How to use a function to do this?


Edit: I tried to iterate each value in the input array and compare to [1, 1], if one of the coordinate is the same, push them to an new array and delete in the input array, and use recursion to do this again. But I stuck by a problem...as I should group [2, 5] and [4, 5] but cannot group [4, 4] and [6, 4]


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

1 Reply

0 votes
by (71.8m points)

You could filter the grouped items and build a new group with the own indices.

const
    data = [[1, 1], [2, 1], [2, 4], [2, 5], [3, 2], [3, 4], [4, 4], [4, 5], [4, 6], [4, 7], [5, 3], [6, 3], [6, 4], [6, 5]],
    offsets = [[-1, 0], [1, 0], [0, -1], [0, 1]],
    groups = data.reduce((r, [i, j]) => {
        const
            own = [];
            temp = r.filter(group => {
                const found = group.some(g => offsets.some(o => i + o[0] === g[0] && j + o[1] === g[1]));
                if (!found) return true;
                own.push(...group);
            });

        return [...temp, [...own, [i, j]]];
    }, []);
    
console.log(groups);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

...