0

How can I sort an array by string value?

If I have an array such as ['you', 'I', 'me', 'me', 'will', 'me'], how can I get all the indexes with the word me at the front of the array?

I have tried using array.sort, but it does not seem to be working.

e.target.value is the an value I am getting from a <select element in the dom.

arr.sort((a, b) => {
    if (a < e.target.value) {
        return -1;
    }
    if (a > e.target.value) {
        return 1;
    }

    return 0;
});

UPDATE: Yury's answer works very well, but what if I need to match two values in an array of objects and have those sorted.

Example:

arr = [
  {id: 1, name: "cookie"}, 
  {id: 2, name: 'foo'}, 
  {id: 3, name: 'bar'}, 
  {id: 2, name: 'foo'}
];

How can I place all the elements with the id '2' and with the name 'foo' at the front of the array?

4
  • so you want to find all index for word "me"? Commented Jun 27, 2017 at 21:29
  • yes, and then move all of those indexes with the word "me" to the front of the array. So index 0, 1, and 2 should be me and then index 3, 4, 5 should be 'you', 'I', and 'will' Commented Jun 27, 2017 at 21:29
  • Shouldn't it be ['me','me','me','I','you','will'] if you want them sorted? Commented Jun 27, 2017 at 21:36
  • the rest of the values dont matter, I just want the key word 'me' to be at the front of the array Commented Jun 27, 2017 at 21:39

2 Answers 2

4

You could use sort

let a = ['you', 'I', 'me', 'me', 'will', 'me'];

a.sort((a, b) => a !== b && b === 'me' ? 1 : 0);

console.log(a)

Sign up to request clarification or add additional context in comments.

3 Comments

Very nice approach (+1) from me.
what if you want have two match by two values in an object? I have updated my question to include this problem.
Use b.propname to access property you want to compare
0
const arr = [
  {id: 1, name: "cookie"},
  {id: 2, name: 'foo'},
  {id: 3, name: 'bar'},
  {id: 2, name: 'foo'}
];

Use the Array.prototype.sort() method on arr using a callback function that switches the order of items only if the first one does not match the given criteria and the second one does.

arr.sort((item1, item2) => {
  if((item1.id !== 2 || item1.name !== 'foo') && (item2.id === 2 || item2.name === 'foo')) {
    return 1;
  }

  return 0;
});

console.log(arr);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.