Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Kiểm tra mảng từ sắp xếp theo bảng chữ cái tùy chỉnh trong JavaScript

Viết hàm kiểm tra mảng từ có sắp xếp đúng thứ tự từ điển theo chuỗi alphabet tùy chỉnh (26 chữ cái trộn lẫn) không.

Ví dụ: arr=['this','is','something','mad'], order='hdetljnopqabcuvwxfgirsykmz' → true.

Ví dụ

const arr = ['this','is','something','mad'];
const order = 'hdetljnopqabcuvwxfgirsykmz';
const isPlacedCorrectly = (arr = [], order) => {
  const { length } = arr;
  for (let i = 0; i < length - 1; i++) {
    for (let j = 0; j < arr[i].length; j++) {
      if (order.indexOf(arr[i][j]) < order.indexOf(arr[i+1][j])) break;
      else if (order.indexOf(arr[i][j]) === order.indexOf(arr[i+1][j])) continue;
      else return false;
    }
  }
  return true;
};
console.log(isPlacedCorrectly(arr, order));

Kết quả

true