angularjs 如何根据对象数组中的用户条目进行筛选

f0brbegy  于 11个月前  发布在  Angular
关注(0)|答案(4)|浏览(129)

我有一个对象数组

let array = [{name: "singpore"}, {name: "French Polynesia"}, {name: "poland"}, {name: "portugal"}]

字符串
我试图实现以下逻辑

array.filter((item) => {
    return item.name.toLowerCase().includes(searchText);
  });


我试图搜索的基础上“po”,当我搜索与po我能够得到所有的记录在同一顺序。
但是我需要按照下面的顺序得到结果来匹配第一个字符
电流输出:

[{name: "singpore"}, {name: "French Polynesia"}, {name: "poland"}, {name: "portugal"}]


预期产出:

[{name: "poland"}, {name: "portugal"}, {name: "singpore"}, {name: "French Polynesia"}]

jgovgodb

jgovgodb1#

您可以在过滤后使用sort()来实现这一点

let array = [
  { name: "singpore" },
  { name: "French Polynesia" },
  { name: "poland" },
  { name: "portugal" }
];

let searchText = "po";

let filteredArray = array
  .filter((item) => item.name.toLowerCase().includes(searchText))
  //compare the index of the search text in each name
  .sort((a, b) => a.name.toLowerCase().indexOf(searchText) - b.name.toLowerCase().indexOf(searchText));

console.log(filteredArray);

字符串

yrwegjxp

yrwegjxp2#

您可以使用indexOf然后使用索引对值进行排序!

let array = [{
  name: "singpore"
}, {
  name: "French Polynesia"
}, {
  name: "poland"
}, {
  name: "portugal"
}]
const searchText = 'po';
console.log(array.filter((item) => {
    return item.name.toLowerCase().includes(searchText);
}).sort((a, b) => {
  const indexA= a.name.toLowerCase().indexOf(searchText);
  const indexB= b.name.toLowerCase().indexOf(searchText);
  return indexA - indexB;
}));

字符串

7xllpg7q

7xllpg7q3#

你也可以试试下面的方法

const array = [
  { name: "singpore" },
  { name: "French Polynesia" },
  { name: "poland" },
  { name: "portugal" }
];

const searchText = "po";

const filteredArray = array.filter((item) => item.name.toLowerCase().includes(searchText))

const sortedArray = filteredArray.sort((a, b) => a.name.toLowerCase().indexOf(searchText) - b.name.toLowerCase().indexOf(searchText));

console.log(sortedArray);

字符串

35g0bw71

35g0bw714#

似乎你的目标是使用一个函数repr来组织你的项目,该函数通过项目名称中术语“po”的首字母索引来表示每个项目。TrueSet是专门为此目的而定制的(请参阅@ut8pia/classifier库)

import {TrueSet} from "@ut8pia/classifier/queue/TrueSet.js";
import {ORDER} from "@ut8pia/classifier/global.js";
import assert from "assert";

const 
    data = [{name: "singpore"}, {name: "French Polynesia"}, {name: "poland"}, {name: "portugal"}],
    expected = [{name: "poland"}, {name: "portugal"}, {name: "singpore"}, {name: "French Polynesia"}];

字符串
您所需要做的就是将数据添加到TrueSet。然而,我想进一步建议,使用Regular Expression作为query可以显著增强所提出的解决方案,使其更简单,功能更强大。

const 
    query = /po/i,
    repr = item => item.name.match(query).index,
    got = TrueSet.of(repr, ORDER.ASCENDING)
        .letAll(data.filter(item => item.name.match(query)));


您可以通过以下方式测试建议的解决方案:

assert.deepEqual(got.toArray(), expected)

相关问题