javascript - 如何从末尾开始查找数组中的元素
问题描述
考虑这个数组:
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”那样接受一个函数。我可以反转数组,找到第一个有效元素,并计算它应该在什么位置将它反转回来。但也许有更好的方法来做到这一点?请注意,我需要知道我需要在哪里、在什么索引处开始切割,因为该索引将用于其他原因。
解决方案
这是我将如何做到的。
我将问题分为2个:修剪左侧部分和修剪右侧部分。
要修剪左边的部分,我们只需遍历数组直到得到一个数字,然后从头到尾对数组进行切片。
要修剪右侧,它只是左侧修剪的镜子。
然后,为了更好地衡量,我添加了一个调用其他 2 个函数以便于使用的函数。
注意:即使我检查了一个number
类型,也可以随意使用不同的检查,例如Number.isInteger()
or 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));
})
推荐阅读
- ios - Flutter 插件 didReceiveRemoteNotification 不起作用
- sql - 查询以查找完成预订还需要多少商品
- php - 刷新视图模板 CakePHP 事件系统
- java - 如何在 lambda 中返回值
- saml-2.0 - Saml2.0 和 Service Provider 请求的数据
- c# - 有没有办法为泛型类提供多个签名
- java - 有没有办法通过swagger注释为不同端点资源使用的模型类编写不同的文档?
- java - 如何解析从清单中的意图过滤器收到的内容数据?
- ignite - 由于锁定,Apache-Ignite 源代码测试确实继续运行
- android - 如何使用 Retrofit 发送发布请求?