0

I have a set of rows I return from a database. They are returned in the form (media_id,order,front_image). One of the media has a front_image value of TRUE. I then have a sort function like so:

.sort(function (m1, m2) {
  if (m1.order < m2.order) {
    val = -1;
  } else if (m1.order > m2.order) {
    val = 1;
  }
  return val;
})

What I'm trying to achieve is to guarantee that if a media has a front_image value of TRUE, it will be the first in the array. I tried adding it as an or statement within the sortFunction but this did not produce the correct results.

3
  • Post the mentioned data. Commented Mar 27, 2017 at 21:04
  • Is TRUE the boolean true? Or is it a string "TRUE"? Commented Mar 27, 2017 at 21:05
  • What did you try exactly? Commented Mar 27, 2017 at 21:11

3 Answers 3

1

Since boolean values coerce to number values 0 (false) and 1 (true), you could sort like this:

.sort(function (m1, m2) {
    return (m2.front_image - m1.front_image) || (m1.order - m2.order);
})

But if the value to give priority is a string "TRUE", then you could just turn that into a boolean expression like this:

.sort(function (m1, m2) {
    return ((m2.front_image=="TRUE") - (m1.front_image=="TRUE")) || (m1.order - m2.order);
})
Sign up to request clarification or add additional context in comments.

Comments

1

One possible approach:

var input = [
  {front_image: false, order: 4},
  {front_image: false, order: 2},
  {front_image: true, order: 3},
  {front_image: false, order: 1},
  {front_image: false, order: 0}
]

var output = input.sort(function (l, r) {
  return (r.front_image - l.front_image)
      || (l.order - r.order)
})

console.log(output)

Comments

1

You could check if front_image is 'TRUE' and move the items to top, then sort by order.

var data = [{ media_id: 1, order: 7, front_image: '' }, { media_id: 3, order: 6, front_image: '' }, { media_id: 6, order: 5, front_image: 'TRUE' }, { media_id: 4, order: 4, front_image: '' }, { media_id: 5, order: 3, front_image: 'TRUE' }, { media_id: 7, order: 2, front_image: '' }, { media_id: 8, order: 1, front_image: '' }];

data.sort(function (a, b) {
    return (b.front_image === 'TRUE') - (a.front_image === 'TRUE') || a.order - b.order;
});

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.