I have array of objects:
let objects = [
{
id: 1,
user_id: 2
},
{
id: 2,
user_id: 2
},
{
id: 3,
user_id: 3
},
{
id: 4,
user_id: 4
},
{
id: 5,
user_id: 4
},
{
id: 6,
user_id: 5
},
{
id: 7,
user_id: 4
},
];
i want to map through of it and give each other colors: red or blue. first two items will have blue, item with id 3 will have color red, next two items will have color blue, item with id 6 will have red and next item with id 7 will have color blue. so i just want to save same items with user_id
with same color but next items with same user_id
must have second color. and i want this to be done in React.js jsx
{objects.map((x, i) => (
<>{objects[i-1] !== undefined && objects[i+1] !== undefined && objects[i].user_id !== objects[i-1].user_id && objects[i].user_id !== objects[i+1].user_id }</>
))}
2
Answers
You have to first find the duplicates and then you can apply condition ,
I have just done some code , you can see or make it better according to your work .
You will need to use global variables to handle this, I have created a sample code for you through online compiler, it will fairly help you achieve what you want.
This will console log your desired condition, in the compiler. And if you are getting confused about how can you use it in jsx, you can try something like this:
This will create extra divs in your htmlbut will get the work done, it sure can be made more sensible if I know more about what you want to create. However this should be enough to give you the idea about how it can be done and you can change it to your needs. e.g maybe instead of console.log(), you may wanna change color though setState.