Home > Net >  Sort 2D array by matching the last values with the first one in the next index
Sort 2D array by matching the last values with the first one in the next index

Time:01-21

So basically, I have this array

array = [[1,0],[2,1],[0,3],[3,2]]

Is there any quick method to convert the array to look like this

array = [[0,3],[3,2],[2,1],[1,0]]

What I want is for the first element of the new array to be always contain 0 in the first spot of the nested array. That's easy enough, because the sort() function does exactly that; the hard part is ordering the new array like the one above.

In the most simplest terms, I'd like for nested arrays to be "connected": see how the 3 of the first nested array matches the other 3 to its right and so on.

Feel free to leave any comments so I can try to explain the problem a little bit better.

CodePudding user response:

For the example you gave the easiest solution would be to sort the 2d array by the second element of each inner array, as follow:

let array = [[1,0],[2,1],[0,3],[3,2]];
array.sort((a, b) => b[1] - a[1]);

In that way you can sort the array with the sort method according to the elements in the inner arrays.

let array = [[1,0],[2,1],[0,3],[3,2]];
array.sort((a, b) => b[1] - a[1]);
console.log(array);

CodePudding user response:

You could take an object as reference and rebuild the array by taking the chained items.

const
    getItems = (reference, value) => {
        const a = reference[value];
        return a ? [a, ...(a[1] === 0 ? [] : getItems(reference, a[1]))] : [];
    },
    array = [[1, 0], [2, 1], [0, 3], [3, 2]],
    reference = array.reduce((r, a) => (r[a[0]] = a, r), {}),
    result = getItems(reference, 0);

console.log(result);

CodePudding user response:

Look at this method:

const array =  [[1,0],[2,1],[0,3],[3,2]];
const result = [...array];

// Put the subarray with the zero element first
// You can use the sort() function but I guess this method
// performs better in terms of time

for (let i = 0; i < result.length;   i) {
  if (result[i][0] === 0) {
    result.unshift(...result.splice(i, 1));
    break;
  }
}

// Now reorder the array so that the last index of a subarray 
// matches with the first index of the other subarray

for (let i = 0; i < result.length;   i) {
  for (let j = i   1; j < result.length;   j) {
    if (result[i][1] === result[j][0]) {
      // recollocate the subarray so that it matches the way we want
      result.splice(i   1, 0, ...result.splice(j, 1));
      break;
    }
  }
}

console.log(result)

  •  Tags:  
  • Related