0

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.

UjinT34
  • 4,784
  • 1
  • 12
  • 26
ale917k
  • 1,494
  • 7
  • 18
  • 37

1 Answers1

0

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 NM times, BUT in filter method, you iterating 1 times in the best case and N!M times in the worst case

kitsoRik
  • 189
  • 3
  • 12