通过比较具有不同元素的两个对象数组来过滤和删除项目

时间:2019-06-28 19:11:29

标签: javascript underscore.js

我有两个数组

arr1 = [{path: "path1"}, {path: "path2"}];
arr2 = [{path: "path1"}];

首先,我想通过比较两个数组来查找从arr1中删除的元素(在本例中为其path1对象),并操纵第一个数组或通过删除该项目覆盖它。在这种情况下,预期的数组是

expArray = [{path: "path2"}]

我尝试使用array.filter方法。

var filteredElements = arr1 .filter(function(obj) {
    return !arr2 .some(function(obj2) {
        return obj.Path === obj2.Path;
    });    
});

但是它仅给出了不同元素的列表,但不支持从数组中删除该元素。有没有办法使用下划线或传统方式做到这一点?

5 个答案:

答案 0 :(得分:2)

您输入的错字是Pathpath。该代码适用于此更改。

var arr1 = [{ path: "path1" }, { path: "path2" }],
    arr2 = [{ path: "path1" }],
    filteredElements = arr1.filter(function(obj) {
        return !arr2.some(function(obj2) {
            return obj.path === obj2.path;
            //         ^             ^
        });
    });
    
console.log(filteredElements);

如果您想突变arr1,则可以拼接不需要的元素,并且由于这会改变长度,因此可以从末尾进行迭代。

var arr1 = [{ path: "path1" }, { path: "path2" }],
    arr2 = [{ path: "path1" }],
    i = arr1.length;

while (i--) {
    if (arr2.some(({ path }) => arr1[i].path === path)) {
        arr1.splice(i, 1);
    }
}

console.log(arr1);

答案 1 :(得分:0)

您可以使用Array#splice从现有数组中删除元素。

let arr1 = [{ path: "path1" }, {  path: "path2"}];

let arr2 = [{ path: "path1" }];

// get length of array for iteration
let l = arr1.length;

// iterate from end to start to avoid skipping index after removing an element
while (l--) {
  // check elemnt present in the array
  if (arr2.some(obj => obj.path === arr1[l].path))
    // remove the element
    arr1.splice(l, 1);
}
console.log(arr1);

答案 2 :(得分:0)

我相信您刚刚将path属性键入为Path,它将返回一个空数组。

代码有效:

var arr1 = [{path: "path1"}, {path: "path2"}];
var arr2 = [{path: "path1"}];

var filteredElements = arr1.filter(function(obj) {
  return !arr2.some(function(obj2) {
    return obj.path === obj2.path;
  });
});

如果要覆盖第一个数组,只需将filteredElements替换为arr1

答案 3 :(得分:0)

您可以使用地图

let arr1 = [{ path: "path1" }, {  path: "path2"}];
const arr2 = [{ path: "path1" }];

const itemsToRemove = arr2.map(a => a.path);
arr1 = arr1.filter(a => !itemsToRemove.includes(a.path));
console.log(arr1);

过滤并重新分配数组值。

答案 4 :(得分:0)

另一种处理方法是从筛选数据的过程中分离用于测试两项是否相等的逻辑。这里,''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Removes an event handler from an event source. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code> ''' Public Class Form1 ''' ''' Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Shown ''' Dim target As Form = Me ''' Dim eventInfo As EventInfo = target.GetType().GetEvent(NameOf(Form.Click)) ''' eventInfo.RemoveEventHandler(target, NameOf(Me.Form1_Click)) ''' End Sub ''' ''' Private Sub Form1_Click(sender As Object, e As EventArgs) Handles MyBase.Click ''' MsgBox(MethodBase.GetCurrentMethod().Name) ''' End Sub ''' ''' End Class ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="eventInfo"> ''' The event information. ''' </param> ''' ''' <param name="target"> ''' The event source. ''' </param> ''' ''' <param name="handlerName"> ''' The name of the delegate to be disassociated from the events raised by <paramref name="target"/>. ''' <para></para> ''' Note that the name is case-sensitive. ''' </param> ''' ---------------------------------------------------------------------------------------------------- <Extension> Public Sub RemoveEventHandler(eventInfo As EventInfo, target As IComponent, handlerName As String) If String.IsNullOrWhiteSpace(handlerName) Throw New ArgumentNullException(NameOf(handlerName)) End If For each handler As [Delegate] in GetEventHandlers(target, eventInfo.Name) If handler.Method.Name.Equals(handlerName, StringComparison.Ordinal) eventInfo.RemoveEventHandler(target, handler) Exit Sub End If Next handler Throw New ArgumentException($"No delegate was found with the specified name: '{handlerName}'", NameOf(handlerName)) End Sub 是一个非常简单的高阶函数。我们传递给它一个函数,该函数报告两个对象是否具有相同的keep属性,并在两个数组上返回一个函数。

然后我们只需使用该功能即可。

path

请注意,我添加了一些属性。这些证明我们只保留第一个数组中的项目。