Hi I am working on a complex application and currently adding two additional properties to objects that match the condition and returning it back. I was able to achieve the expected output, but just wanted to know if there is any other way which is more efficient than what I have tried.
Step 1 : Filtering the array to get only car objects.
Step 2 : Add firstlayer and lastlayer prop to car objects
Step 3 :
- If it is first car object in the filtered array then mark firstlayer as true. If it is last car object in the filtered array then mark lastlayer as true.
Step 4 : concat it with the other non-car objects
Original array:
[{
id: 10,
name: "Truck",
status: "Cancelled"
}, {
id: 11,
name: "Bus",
status: "Approved"
}, {
id: 12,
name: "Car1",
status: "Approved"
}, {
id: 19,
name: "Car2",
status: "Cancelled"
}, {
id: 13,
name: "Car3",
status: "Cancelled"
}]
Expected array:
[{
id: 10,
name: "Truck",
status: "Cancelled"
}, {
id: 11,
name: "Bus",
status: "Approved"
}, {
id: 12,
isFirstLayer: true,
isLastLayer: false,
name: "Car1",
status: "Approved"
}, {
id: 19,
isFirstLayer: false,
isLastLayer: false,
name: "Car2",
status: "Cancelled"
}, {
id: 13,
isFirstLayer: false,
isLastLayer: true,
name: "Car3",
status: "Cancelled"
}]
This is the code I have tried
var array = [
{
"name": "Truck",
"status": "Cancelled",
"id": 10
},
{
"name": "Bus",
"status": "Approved",
"id": 11
},
{
"name": "Car1",
"status": "Approved",
"id": 12
},
{
"name": "Car2",
"status": "Cancelled",
"id": 19
},
{
"name": "Car3",
"status": "Cancelled",
"id": 13
}
];
var i=0;
var arrayLength=array.length;
var newArray = array.filter(function(a) {
if((a.name !='Bus'&&a.name!='Truck'))
{
if(i==0){
a.isFirstLayer=true;
a.isLastLayer=false;
}else if(i==arrayLength-i-1){
a.isFirstLayer=false;
a.isLastLayer=true;
} else{
a.isFirstLayer=false;
a.isLastLayer=false;
}
i++;
};
return a
});
console.log(newArray);
https://jsfiddle.net/fierce_trailblazer/q2uvf06r/24/
Any suggestions to improve the code would be helpful