从多维数组中删除重复项(JS)
Remove duplicates from multidimensional arrays (JS)
我有两个带时间的数组,我想删除重复项,数组可能如下所示:
arr1 = [ ['11:00','12:00','13:00'] ]
arr2 = ['11:00'],['13:00']
所以我尝试首先使用 2 个 for 循环遍历第二个数组,如下所示:
for (i = 0; i < timeslotsBusy.length; i++) {
for (j = 0; j < timeslotsBusy[i].length; j++) {
console.log(timeslotsBusy[i][j]);
}
}
这给了我值:11:00、13:00
现在我尝试使用 while 循环在值匹配时拼接数组,但这不是很好。我也尝试过过滤方法,但没有成功
for (i = 0; i < timeslotsBusy.length; i++) {
for (j = 0; j < timeslotsBusy[i].length; j++) {
for (x = 0; x < timeslotsFree.length; x++) {
timeslotsFree = timeslotsFree[x]
timeslotsFree = timeslotsFree.filter(val => timeslotsBusy[i][j].includes(val))
}
}
}
输入数组(arr1
、arr2
)是multi-dimensional数组,所以需要使用Array.prototype.flat()
函数将它们变成一维数组.
进入1d array
后,可以使用Array.prototype.filter
函数获取不重复成员。 (要检查 arr2 是否包含该项目,您可以使用 Array.prototype.includes
函数。)。
const arr1 = [ ['11:00','12:00','13:00'] ];
const arr2 = [ ['11:00'],['13:00'] ];
const arr1Flat = arr1.flat();
const arr2Flat = arr2.flat();
const output = arr1Flat.filter((item) => !arr2Flat.includes(item));
console.log(output);
我有两个带时间的数组,我想删除重复项,数组可能如下所示:
arr1 = [ ['11:00','12:00','13:00'] ]
arr2 = ['11:00'],['13:00']
所以我尝试首先使用 2 个 for 循环遍历第二个数组,如下所示:
for (i = 0; i < timeslotsBusy.length; i++) {
for (j = 0; j < timeslotsBusy[i].length; j++) {
console.log(timeslotsBusy[i][j]);
}
}
这给了我值:11:00、13:00
现在我尝试使用 while 循环在值匹配时拼接数组,但这不是很好。我也尝试过过滤方法,但没有成功
for (i = 0; i < timeslotsBusy.length; i++) {
for (j = 0; j < timeslotsBusy[i].length; j++) {
for (x = 0; x < timeslotsFree.length; x++) {
timeslotsFree = timeslotsFree[x]
timeslotsFree = timeslotsFree.filter(val => timeslotsBusy[i][j].includes(val))
}
}
}
输入数组(
arr1
、arr2
)是multi-dimensional数组,所以需要使用Array.prototype.flat()
函数将它们变成一维数组.进入
1d array
后,可以使用Array.prototype.filter
函数获取不重复成员。 (要检查 arr2 是否包含该项目,您可以使用Array.prototype.includes
函数。)。
const arr1 = [ ['11:00','12:00','13:00'] ];
const arr2 = [ ['11:00'],['13:00'] ];
const arr1Flat = arr1.flat();
const arr2Flat = arr2.flat();
const output = arr1Flat.filter((item) => !arr2Flat.includes(item));
console.log(output);