I have the following array:
[
{name:"jhon",surname:"connor",age:21},
{name:"jhonny",surname:"lator",age:22},
{name:"celia",surname:"mcgregor",age:23},
{name:"raul",surname:"fernandez",age:25},
{name:"marcela",surname:"fernandez",age:25},
{name:"omar",surname:"caster",age:26},
{name:"luna",surname:"potter",age:30},
{name:"harry",surname:"potter",age:30},
]
and I want to have the following order:
[
{order:1,name:"jhon",surname:"connor",age:21},
{order:2,name:"jhonny",surname:"lator",age:22},
{order:3,name:"celia",surname:"mcgregor",age:23},
{order:4,name:"raul",surname:"fernandez",age:25},
{order:4,name:"marcela",surname:"fernandez",age:25},
{order:5,name:"omar",surname:"caster",age:26},
{order:6,name:"luna",surname:"potter",age:30},
{order:6,name:"harry",surname:"potter",age:30},
]
If the last name and age are the same, don't count in the iteration of the order.
in javascript.
CodePudding user response:
Here you go (Added descriptive comments in the below code snippet) :
// Input array
const arr = [
{name:"jhon",surname:"connor",age:21},
{name:"jhonny",surname:"lator",age:22},
{name:"celia",surname:"mcgregor",age:23},
{name:"raul",surname:"fernandez",age:25},
{name:"luna",surname:"potter",age:30},
{name:"marcela",surname:"fernandez",age:25},
{name:"omar",surname:"caster",age:26},
{name:"harry",surname:"potter",age:30}
];
// For safer side, First sort the array in ascending order based on age property.
arr.sort((a, b) => a.age - b.age);
// Logic to add the order property in each object of arr.
const res = arr.map((obj, index) => {
obj.order = index === 0 ? 1 : (arr[index - 1].surname === obj.surname && arr[index - 1].age === obj.age) ? arr[index - 1].order : arr[index - 1].order 1
return obj;
});
// Output
console.log(res);
CodePudding user response:
I’d implement it like this
const array = [] // your array of objects
const newOrderedArr = array.map((obj, i) => {
if(i === 0) return { …obj, order: 1 };
return { …obj, order: (array[i - 1].surname === obj.surname && array[i - 1].age === obj.age)? array[i - 1].order : array[i - 1].order 1};
})
Assuming that you only check the previous object for similar surnames and ages