[英]How to get index of removed element in the sub array
I have an array all = [2,3,4,12, 55,33]
and ar1 = [12, 55, 33]
which is a sub array of all
(starts from 12). 我有一个数组
all = [2,3,4,12, 55,33]
和ar1 = [12, 55, 33]
all = [2,3,4,12, 55,33]
,这是all
的子数组(从12开始)。
When I remove a value from all
which is a part of ar1
(ex:12) how do I get the index of that value in ar1
(for 12 it is 0) so that I can remove it from ar1
also. 当我从
ar1
(ex:12)的all
部分中删除一个值时,如何获取ar1
中该值的索引(对于12则为0),以便也可以从ar1
删除它。
Edit: I actually have objects in my array. 编辑:我实际上在我的数组中的对象。 I used numbers here as example
我在这里以数字为例
Since you specified that your array contains objects, you should give each object an individual id
, so that you can use the id
to filter it. 由于您指定数组包含对象,因此应为每个对象指定一个单独的
id
,以便可以使用该id
进行过滤。 Your objects, apart from the id
, can hold any other data. 除了
id
之外,您的对象还可以保存其他任何数据。
You can then use Array.findIndex
to find the index of the corresponding object. 然后,您可以使用
Array.findIndex
查找相应对象的索引。
Example: 例:
const arr = [{ id: "abc" }, { id: "def" }];
arr.findIndex (itm => itm.id === "def") // Returns 1
Alternatively, in case you cannot add an id
, you will have do do a deep object comparison (which is not 100% accurate, but works in most cases). 另外,如果您不能添加
id
,则可以进行深层对象比较(虽然不是100%准确,但在大多数情况下还是可以的)。 You could either use a standalone implementation, or, for example, Lodash's _.isEqual
. 您可以使用独立的实现,也可以使用Lodash的
_.isEqual
。
Actually, you can use Array#splice() to remove the element from the first array, then check for its index
using Array#findIndex() and then remove it from the second array
. 实际上,您可以使用Array#splice()从第一个数组中删除元素,然后使用Array#findIndex()检查其
index
,然后从第二个array
删除它。
var [removed] = all.splice(3, 1);
var index = ar1.findIndex(el => el.val == removed.val);
if (index !== -1) {
ar1.splice(index, 1);
}
Demo: 演示:
var all = [{ val: 2}, { val: 3}, {val: 4}, {val: 12}, {val: 55 }, {val: 33}], ar1 = [{val: 12}, {val: 55}, {val: 33}]; var [removed] = all.splice(3, 1); console.log(removed); var index = ar1.findIndex(el => el.val == removed.val); if (index !== -1) { ar1.splice(index, 1); } console.log(ar1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.