如何在数组中从末尾开始查找元素



考虑这个数组:

const arr = [
[1, 2, 3, 4, 3, 2, 4]
,[1, 0, 3, 4, 3, 2, 0]
,[undefined, 0, null, 4, 3, null, 0]
,[undefined, undefined, 5, 7, undefined, null, undefined]
];

我的任务是修剪每个数组。有效值是整数(或浮点值,相同)。0也被认为是有效的。在这种情况下,修剪意味着数组需要在开始和结束时进行修剪。

在上面的例子中:

arr[0] does not need to remove any element
arr[1] does not need to remove any element
arr[2] needs to remove arr[2][0]
arr[3] needs to remove arr[3][0], arr[3][1] from the beginning and arr[3][4], arr[3][5], arr[3][6] at the end.

我的方法如下:

首先找出数组中的第一个有效元素:

const foundStartIndex = arr[x].findIndex(el => el >= 0);    

这将帮助我在开始时对数组进行切片。

但是,我该如何从哪里开始去除呢?有一个";lastIndexOf";但看起来它并没有以同样的方式接受函数";findIndex";做我可以反转数组,找到第一个有效元素,并计算它应该在哪里,何时将反转回来。但也许还有更好的方法呢?请注意,我需要知道在哪里,在什么指数,我需要开始削减,因为该指数将用于其他原因。

按照您的方法,我建议如下:

const reverseEndIndex = arr[x].reverse().findIndex(el => el >= 0);
const foundEndIndex = arr[x].length - 1 - reverseLastIndex;

第二个代码行将反转数组中的索引转换为非反转数组的索引。

以下是我的操作方法。

我把问题分为两部分:修剪左边的部分和修剪右边的部分。

要修剪左边的部分,我们只需要遍历数组,直到得到一个数字,然后从数组的开头一直切片到那个点。

要修剪右侧,它只是左侧修剪的一面镜子。

然后,为了便于使用,我添加了一个调用其他两个函数的函数。

注意:即使我检查了number类型,也可以随意使用不同的检查,如Number.isInteger()element >= 0

/**
* @param {Array} arr
*/
function leftTrimArray(arr) {
let i = 0
let element = arr[i]
while (typeof element !== 'number') {
i++
element = arr[i]
}
return arr.slice(i)
}
/**
* @param {Array} arr
*/
function rightTrimArray(arr) {
let i = arr.length - 1
let element = arr[i]
while (typeof element !== 'number') {
i--
element = arr[i]
}
return arr.slice(0, i + 1)
}
function trimArray(arr) {
return rightTrimArray(leftTrimArray(arr))
}
const arrs = [
[1, 2, 3, 4, 3, 2, 4],
[1, 0, 3, 4, 3, 2, 0],
[undefined, 0, null, 4, 3, null, 0],
[undefined, undefined, 5, 7, undefined, null, undefined]
];
arrs.forEach(arr => {
console.log(trimArray(arr));
})

从您的问题中还不清楚为什么需要使用索引"由于其它原因";,但如果你需要只包含数字的干净数组,你可以在它们上面map,然后filter去掉所有不是null或数字的东西。

const arr = [
[1, 2, 3, 4, 3, 2, 4],
[1, 0, 3, 4, 3, 2, 0, 'Bob'],
[undefined, 0, null, 4, 3, null, 0, 0.2],
[undefined, undefined, 5, 7, undefined, null, undefined]
];
const out = arr.map(n => n.filter(el => {
return el !== null && !isNaN(el);
}));
console.log(out);

最新更新