skip to Main Content

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


  1. Use Math.abs() to measure distance:

    var sorteditems = objects.sort((a, b) => {   
          let diff1 = Math.abs(numbereddifference-a.feat[0].value);
          let diff2 = Math.abs(numbereddifference-b.feat[0].value);
           
          return diff1 - diff2;
        });
        
        console.log(sorteditems)
    

    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

    Login or Signup to reply.
  2. It’s not clear what you’re trying to do with a.id.match('heal') but I’ll point out that a.id is "obj1", not "heal". Also, bothpdiff isn’t defined in your example.

    You can sort them by subtracting the absolute difference between value and numberdifference for the items to be compared.

    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;
    
    const sorted = objects.sort(({feat: a}, {feat: b}) => {
      return Math.abs(numberdifference - a[0].value) - Math.abs(numberdifference - b[0].value);
    })
    
    console.log(sorted); // 500, 350, 125, 1000
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search