我有两个数组,一个现有集合和一个新数组。我想通过以下方式将两者结合起来:
- 从现有对话中的所有元素开始
- 对于新数组中的每个项目,如果现有数组中不存在具有相同
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/