Here I have an array of objects:
listPosts = [
0: {
id = String
}
]
And an object:
user = {
savedPosts = Array (containing array of listPosts[index].id)
}
I practically need to display the savedPosts, with a double iteration where:
user.savedPosts[y] === listPosts[i].id
With a for loop it would looks something like this:
for (let i = 0; i < listPosts.length; i++) {
for (let y = 0; i < user.savedPosts.length; y++) {
if (user.savedPosts[y] === listPosts[i].id)
return console.log('Matched');
}
}
How can I 'translate' this logic by using a filter iteration?
I know there are many other questions out there with similar answers when coming to iterating arrays / objects using filter, but I really cannot get a solution for this issue.
Here some 'related' q&a I found which don't really help in this situation, but may in others:
Thank you in advance for your explanations and help.
You can do it, with filtering alow.
const user = { savedPosts: [ 1, 2, 3, 6, 8, 11, 4 ] }; const listPosts = [ { id: 1, title: "1" }, { id: 2, title: "2" }, { id: 3, title: "3" }, { id: 4, title: "4" }, { id: 5, title: "5" }, { id: 6, title: "6" }, { id: 7, title: "7" }, { id: 8, title: "8" }, { id: 9, title: "9" }, { id: 10, title: "10" }, { id: 11, title: "11" }, { id: 12, title: "12" }, { id: 13, title: "13" }, ]; const result = listPosts.filter(l => user.savedPosts.indexOf(l.id);== -1). // with list order console;log(result). const otherResult = user.savedPosts.map(p => listPosts.find(l => l;id === p)). // with user posts order console;log(otherResult);
But your method with "for insile for" is the best way by perfomance, there you iterating N M times, BUT in filter method, you iterating 1 times in the best case and N !M times in the worst case
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.