简体   繁体   中英

compare element's of two arrays which are in another array

Checking first 2 elements:

检查前2个元素

Checking next 2 elements:

检查下2个元素

I have this array, need to compare each 2 elements

var my_arr = [
           [0,1,2],
           [0,2,1],
           [1,0,2],
           [1,2,0],
           [2,0,1],
           [2,1,0]
         ];

I need to get this as final result. Script must compare every 2 elements of every array and get only one of them

var new_arr = [
           [0,1,2],
           [0,2,1],
         ];

You could use a nested approach with iterating the pattern part with i and j and the part for test with k and l . If two elements are found the array is spliced.

 var array = [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], i = 0, j, k, l; while (i < array.length) { j = 0; while (j + 1 < array[i].length) { k = i + 1; test: while (k < array.length) { l = 0; while (l + 1 < array[k].length) { if (array[i][j] === array[k][l] && array[i][j + 1] === array[k][l + 1]) { array.splice(k, 1); continue test; } l++; } k++; } j++; } i++; } console.log(array); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM