I have an array of objects like this:
var objects = [
{id: "obj1",
feat: [{
id: "heal",
value: 125
}]
},
{id: "obj2",
feat: [{
id: "heal",
value: 350
}]
},
{id: "obj3",
feat: [{
id: "heal",
value: 500
}]
},
{id: "obj4",
feat: [{
id: "heal",
value: 1000
}]
}
]
var numberdifference = 498;
I want to sort the objects being on top the object which value is closer to numberdifference
var sorteditems = objects.sort((a, b) => {
if(a.id.match('heal') && b.id.match('heal')) {
let diff1 = bothpdiff-a.feat[0].value;
let diff2 = bothpdiff-b.feat[0].value;
return diff1 - diff2;
});
console.log(sorteditems);
But I can’t make it work. In this example obj3 should be on top followed by obj2.
2
Answers
Use
Math.abs()
to measure distance:Also remove condition with ‘heal’, because it’s wrong (flow never goes there). Better to use filter to remove all elements without the ‘heal’ as id
It’s not clear what you’re trying to do with
a.id.match('heal')
but I’ll point out thata.id
is"obj1"
, not"heal"
. Also,bothpdiff
isn’t defined in your example.You can sort them by subtracting the absolute difference between
value
andnumberdifference
for the items to be compared.