javascript - 如何简化根据属性组合两个数组的 es6 函数?

标签 javascript arrays ecmascript-6

我有两个数组,一个现有集合和一个新数组。我想通过以下方式将两者结合起来:

  • 从现有对话中的所有元素开始
  • 对于新数组中的每个项目,如果现有数组中不存在具有相同 id 的元素,那么我们将添加它。
  • 如果确实存在具有相同 id 的项目,则仅当新项目的 updated 属性值大于以下值时,我们才会替换现有项目现有属性的updated 属性。
  • 如果它不大于我们就忽略新元素。

我们不能修改传入的数组,并且必须返回组合数组。

function combineConversations(newConversations, existingConversations) {
  const combined = [...existingConversations];
  newConversations.forEach(conversation => {
    const existingConversationIndex = indexOfObject(combined, conversation.id , 'id');
    if (existingConversationIndex && conversation.updated > combined[existingConversationIndex].updated) {
      combined[existingConversationIndex] = conversation;
    } else {
      combined.push(conversation);
    }
  });
  return combined;
}

我想知道执行此操作的完整功能方法。有吗?

最佳答案

是的,你可以用这样的函数式方法来做到这一点:

var oldChat = [
  {id: 1, updated: 1985, data: "coucou"},
  {id: 2, updated: 1995, data: "au revoir"},
  {id: 3, updated: 2003, data: "bonjour"}
];

var newChat = [
  {id: 1, updated: 1986, data: "coucou"},
  {id: 2, updated: 2004, data: "bye"},
  {id: 3, updated: 2001, data: "bonjour"},
  {id: 4, updated: 2008, data: "vive le sport"}
];

var result = (oldChat, newChat) => newChat.concat(oldChat).sort((a,b) => a.id-b.id).filter((item, index, arr) => index < arr.length - 1 ? item.id !== arr[index+1].id : true);
console.log(result(oldChat, newChat)); //[ { id: 1, updated: 1986, data: 'coucou' },
//{ id: 2, updated: 2004, data: 'bye' },
//{ id: 3, updated: 2003, data: 'bonjour' },
//{ id: 4, updated: 2008, data: 'vive le sport' } ]

编辑:我合并了新旧数组并对它们进行排序以获得具有相同 id 的相邻元素,然后过滤以保留具有唯一 id 或最新更新的元素

关于javascript - 如何简化根据属性组合两个数组的 es6 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39931146/

相关文章:

javascript - AngularJS 弹出对话框中有多个输入框?

javascript - react : Nothing was returned while the ternary always returns something

arrays - 具有特定值的数组

javascript - "static method"与 "object property method"

javascript - 如何同步触发两个异步函数?

javascript - cordova 3.5.0 上的本地通知不起作用?

javascript - 网络套接字握手。从 ws 到 wss

c - 如何读取文本文件中的逗号分隔行并将其字段插入到结构指针数组中?

python - 将 numpy 数组保存到 csv 会产生不匹配错误

javascript - ES6 转译器中的导入/导出