0

Suppose i have an array which has books id, For Example [1,42,34,56,21,8,88,32] all distinct, and i have an array of book objects example :

[
 {
  BookId: 34, BookName: Foo1
 },
 {
  BookId: 56, BookName: Bar1
 },
 {
  BookId: 1, BookName: Foo2
 },
.....
]

Books are not in same order as book ids array, although size of both arrays is equal, i want a resulting array of books, in-order with book id array.

I can use nested loops, but that would be m×n complexity. So basically i wanna perform something like SQL join.

Is it possible to reduce the complexity?

Akif Hussain
  • 475
  • 5
  • 22
Bharat Sharma
  • 11
  • 1
  • 3
  • Well, if you don't want to do it in `controllers` then you should specify which database are you using. IF `SQL` then there are several ways to perform `JOIN` while calling the API. – Akif Hussain Nov 26 '19 at 10:36
  • I have two databases, i get array of book ids from mongo, and then books from postgres, so its not possible to perform a join – Bharat Sharma Nov 26 '19 at 11:05

1 Answers1

-1

Try this:

const ids = [1,34,56,21];
const books = [
{BookId: 34, BookName: 'Foo34'},
{BookId: 56, BookName: 'Bar56'},
{BookId: 1, BookName: 'Foo1'},
{BookId: 21, BookName: 'Foo21'},
];

books.sort((a, b)=> ids.indexOf(a.BookId) - ids.indexOf(b.BookId));
console.log(books);
Max
  • 1,020
  • 7
  • 13
  • this works!!! idk why it was down voted, the other thread didn't work in my case as arrays were already sorted in that case – Bharat Sharma Nov 26 '19 at 17:17