[英]array difference based on positions in javascript
I have tried multiple approach to solve this problem, any heads up would be great help. 我已经尝试了多种方法来解决此问题,任何注意都将大有帮助。 I'm having a drag and drop functionality using
ng-draggable.js
in my project,so initially I set the elements to array A
, and when I drag and drop an element inside the array, I don't know how to capture the changed elements in that array with positions. 我在项目中使用
ng-draggable.js
具有拖放功能,因此最初我将元素设置为array A
,当我将元素拖放到数组中时,我不知道如何捕获更改了该数组中具有位置的元素。 say A = [1,2,3]
now customer changes the position with drag and drop feature. 例如,
A = [1,2,3]
现在客户可以通过拖放功能更改头寸。 Its becomes B = [2,1,3]
. 它变成
B = [2,1,3]
。 when I do a diff of A and B
, I must get the changed elements [2,1]
with positions, so that I can send it to server th elements with updated positions. 当我对
A and B
进行比较时,我必须获取具有位置的更改后的元素[2,1]
,以便可以将其发送到具有更新位置的服务器上的元素。 I have tried underscore.js _.difference(A,B)
, it gives me empty array, 我已经尝试过
underscore.js _.difference(A,B)
,它给了我一个空数组,
It seems that .difference()
returns set differences, but the index is important here: 似乎
.difference()
返回了设置差异,但是索引在这里很重要:
var a = [1,2,3]; var b = [2,1,3]; var diff = a.filter(function(value, index) { return b[index] != value; }); //[1,2] var positions = diff.map(function(value) { return b.indexOf(value); }); // [0,1]
Then, for each of those values you need to find the position in array b
using .indexOf()
然后,对于每个这些值,您都需要使用
.indexOf()
在数组b
找到位置
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.