1

Here i have Two arrays,

var Usercar = [
            {_id: 1, name: bmw, color: red},
            {_id: 2, name: Ford, color: black},
            {_id: 3, name: Volkswagen, color: black},
          ]

var Userfavorite = [1,3]

I want to show user favorite cars using map,like

            Usercar.map((car,index)=>{
                  Userfavorite.map(re=>{
                    if (car._id === re)
                    {
                     <p>{car.name}</p>
                    }
                  })
                })

My question is, This mapping will effects my JSX page ?, because i have multiple mapping like this in a page and how to optimize this mapping

I saw slow page load currently

10
  • can you change userCar structure to object instead of an array ? then you can simply loop over userFavourite array and get values from userCar. Commented Mar 20, 2020 at 5:36
  • Yes i got you, but i have more stuffs on Usercar's array :( Commented Mar 20, 2020 at 5:39
  • This userCar array comes from any api ? or you locally build it ? Commented Mar 20, 2020 at 5:40
  • 1
    How did you identify this loop as the cause of the slowdown? Commented Mar 20, 2020 at 6:38
  • 1
    These loops then :) Commented Mar 20, 2020 at 7:26

5 Answers 5

3

If there are multiple places where these mappings are required, I might consider converting the Usercar to a Map. So then only one looping will be required, reducing complexity to O(n).

const userCarMap = new Map(Usercar.map(car => [car._id, car]));
// Map(3) {1 => {…}, 2 => {…}, 3 => {…}}



Userfavorite.map(fav => {
 const carInfo = userCarMap.get(fav);
 return <p>{carInfo.name}</p>
});

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

1

var Usercar = [
            {_id: 1, name: 'bmw', color: 'red'},
            {_id: 2, name: 'Ford', color: 'black'},
            {_id: 3, name: 'Volkswagen', color: 'black'},
          ]

var Userfavorite = [1,3]

const convertArrayToObject = (array, key) => {
  const initialValue = {};
  return array.reduce((obj, item) => {
    obj[item[key]] = item; 
    return obj;
  }, initialValue);
};

var result = 
  convertArrayToObject(
    Usercar,
    '_id',
  );
  
console.log(Userfavorite.map(x => '<p>'+result[x].name+'</p>'));

3 Comments

It's probably better to use a Map nowadays rather than an object but it's still a good solution. A Map is just more modern.
I'm assuming these arrays are large if we are talking about performance... the destructuring obj into a new object is a bit memory thrashy.
obj[item[key]] = item; return obj
0

You can use filter, includes and map method so that it will have a complexity of O(n) instead of O(n²) like so:

Usercar.filter(item => Userfavorite[item._id] != undefined)
    .map((car,index)=>{
    return (
        <p>{car.name}</p>
    )
});

UPDATE Changed .includes to a simple check of existence

5 Comments

Thanks alot for you answer dear , will check :)
filter() -> .includes() is still O(n^2) since you have to do an iteration every iteration.
@VLAZ here filter,includes then mapping, do you have any better idea ?
@HarryEdward check my updated answer. it is now O(n)
It's O(n) but it's also wrong. Userfavorite[item._id] will not give you the correct item - you're using the ID as n index, but with OP's example _id = 3 would fail, even if it's present in Userfavorite because the array only has two items, and fetching index 3 will not find the item with value 3.
0

var Usercar = [
  { _id: 1, name: "bmw", color: "red" },
  { _id: 2, name: "Ford", color: "black" },
  { _id: 3, name: "Volkswagen", color: "black" }
];

var Userfavorite = [1, 3];

var res = Usercar.filter(car => Userfavorite.includes(car._id))
      .map(item => item.name);

console.log(res);

1 Comment

This is still O(n^2) since .includes does another O(n) iteration within the O(n) from the .filter
0

You do not need to explicitly loop on Userfavorite. You just need check if id exists and return JSX.

var Usercar = [
  {_id: 1, name: bmw, color: red},
  {_id: 2, name: Ford, color: black},
  {_id: 3, name: Volkswagen, color: black},
]

var Userfavorite = [1,3]

Usercar.map((car, index) => Userfavorite.includes(car._id) ? <p> { car.name } </p> : null);

11 Comments

@VLAZ what about this answer :)
Still O(n^2). Again, .includes is O(n) and it's executed with every of the O(n) callbacks of .map. So, it's a nested loop.
@HarryEdward My best guess would be O(n*m) where n is Usercar's length and m is Userfavourite's length
Right, O(n*m) is more accurate. Point is it's a nested loop. Without removing the nested looping, the complexity is going to be a lot more than really needed.
I'm not really sure what the slowdown is, to be honest. If you need to do A LOT of loops based on also looping to find an item in Usercar, then a lookup table solves that. But I've no idea whether that's the case or if time complexity of algorithms is even the root cause of it. We need the bigger picture here. I'm just throwing suggestions since most replies were not much of an improvement over OP's solution in terms of complexity.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.