xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

js sort string array by alphabetically All In One

js sort string array by alphabetically All In One

const arr = ["abc", "xyz", "acb"];
arr.sort(); 
// ['abc', 'acb', 'xyz'] ✅
const arr = ["abc", "xyz", "acb"];

const obj = {};
for (let item of arr) {
    obj[item] = item;
}
Object.keys(obj);
// ['abc', 'acb', 'xyz'] ✅
      

demo

const arr = ["let1 art can", "let2 own kit dig", "let3 art zero"];


arr.sort((a, b) => {
  const arr1 = a.split(' ');
  const arr2 = b.split(' ');
  if(arr1.slice(1).join() !== arr2.slice(1).join()) {
      // sort string array ???
      const temp = [arr1.slice(1).join(), arr2.slice(1).join()].sort((x, y) => x - y > 0 ? -1 : 1);
      return temp === arr1.slice(1).join() ? -1. : 1;
  } else {
      const temp = [arr1[1], arr2[1]].sort((x, y) => x - y > 0 ? -1 : 1);
      return temp === arr1[1] ? -1. : 1;
  }
});
// ['let1 art can', 'let2 own kit dig', 'let3 art zero']. ❌

// ✅  ["let1 art can",  "let3 art zero", "let2 own kit dig"];

solution


/**
 * @param {string[]} logs
 * @return {string[]}
 */
var reorderLogFiles = function(logs) {
  const strs = logs.filter(log => {
    const arr = log.split(' ');
    return !arr[1].match(/[0-9]/g);
    // return arr[1].match(/^[0-9]/g);
    // return arr[1].match(/^\W/g);
    // return arr[1].match(/\w/g);
  });
  const nums = logs.filter(log => {
    const arr = log.split(' ');
    return arr[1].match(/[0-9]/g);
  });
  const result = strs.sort((a, b) => {
    const arr1 = a.split(' ');
    const arr2 = b.split(' ');
    if(arr1.slice(1).join() !== arr2.slice(1).join()) {
        // 内容不同
        const temp = [arr1.slice(1).join(), arr2.slice(1).join()].sort();
        // 升序
        return temp[1] === arr1.slice(1).join() ? 1 : -1;
    } else {
        // 内容相同,比较 标识符
        const temp = [arr1[0], arr2[0]].sort();
        // 降序
        return temp[0] === arr1[0] ? -1 : 1;
    }
  });
  return [...result, ...nums];
};

https://leetcode.com/problems/reorder-data-in-log-files/

js sort asc & js sort desc

升序 / 降序

const arr = ['X', 'Y', 'A', 'B'];

const upOrder = [...arr].sort((a, b) => {
  const temp = [a, b].sort();
  // 升序 asc / Ascending
  return temp[0] === a ? -1 : 1;
});


const downOrder = [...arr].sort((a, b) => {
  const temp = [a, b].sort();
  // 降序 desc / Descending
  return temp[0] === a ? 1 : -1;
});

console.log('upOrder =', upOrder);
// ["A", "B", "X", "Y"]

console.log('downOrder =', downOrder);
// ["Y", "X", "B", "A"]

// keep origin === [...arr]
console.log('arr =', arr);
// ["X", "Y", "A", "B"]


refs



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-03-13 22:32  xgqfrms  阅读(53)  评论(2编辑  收藏  举报