Sorting an array in javascript with quotes

I have an array

var arr = ['hello','"end" two', 'end one', 'yes', 'abc' ];

I need to sort it as below

// abc,  end one, "end" two, hello, yes

What should I do?

+4
source share
4 answers

You can choose String#localeCompare.

ignorePunctuation

Should punctuation be ignored. Possible values: trueand false; used by default false.

var array = ['hello', '"end" two', 'end one', 'yes', 'abc'];

array.sort(function (a, b) {
    return a.localeCompare(b, undefined, { ignorePunctuation: true });
});

console.log(array);
Run codeHide result
+5
source

function sortarray(a,b) {
  a = a.replace(/"/g,'');
  b = b.replace(/"/g,'');

    return (a < b ? -1 : 1);
}

keys = ['hello','"end" two', 'end one', 'yes', 'abc' ]

var sorted = keys.sort(sortarray);
alert(sorted);
Run codeHide result

This creates a function that can be used directly where you want.

+2
source

function sortarray(one,two) {
  one = one.replace(/"/g,'');
  two = two.replace(/"/g,'');

    return (one < two ? -1 : 1);
}

keys = ['hello','"end" two', 'end one', 'yes', 'abc' ]

var sorted = keys.sort(sortarray);
alert(sorted);
Hide result
+1

, , . , :

const sortValues = arr.map(elt => elt.replace(/"/g, ''));

, 0 :

const sortIndexes = arr.map((_, i) => i)
  .sort((a, b) => sortValues[a].localeCompare(sortValues[b]));

Then reorder the input array based on the sorted indices:

const result = sortIndexes.map(i => arr[i]);
0
source

Source: https://habr.com/ru/post/1683788/


All Articles