简体   繁体   中英

javascript array sort strings and numbers

I would like to sort array with strings and numbers.

var toSort = ['100', 'Calc', '30', '43', '52', '16', '10', '11', '12', 'Calc', '2', 'N/A', '8'];

the expected behavior is when sorting the string will be sorted at the end of the list for both states (asc and desc), like: asc:

['2','8','10','11','12','16','30','43','52','100','Calc','Calc','N/A']

desc:

['100','52','43','30','16','12','11','10','8','2','Calc','Calc','N/A']

I have it for asc state:

toSort.sort(function (a,b) {
  if (a === 'Calc') return 1;
  else if (a === 'N/A') return 1;
  else return a.localeCompare(b, undefined, { numeric: true});
});

console.log(toSort);

any ideas for desc state? tnx

You could check if a value isFinite .

 const array = ['100', 'Calc', '30', '43', '52', 'Calc', '16', '10', 'N/A', '123', '11', '12', 'Calc', '2', 'N/A', '8']; array.sort((a, b) => isFinite(b) - isFinite(a) || a - b || a.localeCompare(b)); console.log(...array); array.sort((a, b) => isFinite(b) - isFinite(a) || b - a || a.localeCompare(b)); console.log(...array);

You can create an object with 2 properties numbers , strings with reduce , after that you can pass that object where you can sort accordingly and return the result.

finalResult = result after sorting numbers + result after sorting strings.

 var toSort = [ "100", "Calc", "30", "43", "52", "16", "10", "11", "12", "Calc", "2", "N/A", "8", ]; function sort({ strings, numbers }, type) { if (type === "asc") { return [...numbers.sort((a, b) => a - b), ...strings.sort((a, b) => (a > b? 1: -1)), ]; } else { return [...numbers.sort((a, b) => b - a), ...strings.sort((a, b) => (a > b? -1: 1)), ]; } } const obj = toSort.reduce( (acc, curr) => { if (/\d+/g.test(curr)) acc.numbers.push(curr); else acc.strings.push(curr); return acc; }, { strings: [], numbers: [] } ); console.log(sort(obj, "asc")); console.log(sort(obj, "dsc"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM