I have update array function I want to simplify this code if possible.
This update function is about updating and comparing the value of array.
The data will be compared inside the fruit_temp
example data of fruit_temp fruit_db_id is and existing id inside the database.
fruit_temp = [{
fruit_db_id: 71,
fuit_id : 1,
name : 'papaya'
}, {
fruit_db_id: 73,
fuit_id : 3,
name : 'apple'
}];
I will get and read the fruit_temp value and when its to perform update function it will compare the existing and the new value that will inserted. This is the solution for this update function. I just want to know if this code can be simplify or not.
const updateFruit = () =>
{
finalFruit_temp = [];
let fruit = $('#fruit').val(); //getting fruit value
fruit = fruit.map(Number); //convert string value to integer
fruit.map((el) =>{
let fruitData = fruit_temp.filter((e) => e.id === el)[0]; //return index if compare true
finalFruit_temp.push({
"fruit_db_id" :(fruitData == undefined) ? null : fruitData.fruit_db_id,
"fruit_id" :(fruitData == undefined) ? el : fruitData.id,
"status" :true
});
});
fruit_temp.map((el) =>{
let checkedFruit= fruit.includes(el.id);
if(checkedFruit == false)
{
finalFruit_temp.push({
"fruit_db_id" :el.db_id,
"fruit_id" :el.id,
"status" :false
});
}
});
}
This code seems well simplified, but I see a few things you could do to make it even shorter. Defining variables in a one liner and changing the last condition statement.
const updateFruit = () => {
finalFruit_temp = [];
let fruitData, fruit = $('#fruit').val().map(Number);
fruit.map((el) => {
fruitData = fruit_temp.filter((e) => e.id === el)[0];
finalFruit_temp.push({
"fruit_db_id" :(fruitData == undefined) ? null : fruitData.fruit_db_id,
"fruit_id" :(fruitData == undefined) ? el : fruitData.id,
"status" :true
});
});
fruit_temp.map((el) => {
if(!fruit.includes(el.id)){
finalFruit_temp.push({
"fruit_db_id" :el.db_id,
"fruit_id" :el.id,
"status" :false
});
}
});
}