首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >按特定顺序对名称数组进行排序

问按特定顺序对名称数组进行排序
EN

Stack Overflow用户
提问于 2019-06-22 14:49:41
回答 3查看 101关注 0票数 1

我正在开发一个不协调机器人,我有一个按字母顺序排列的字符数组列表。我正在尝试做的是,当有人使用$info (name)命令时,机器人将使用for循环查看数组,并从数组中抓取与字符串开头最接近的块匹配的名字。举个例子:

代码语言:javascript
复制
let namelist = ['adam', 'al', 'albert', 'bertie', 'cole'];

$info a 
/*would grab Adam because he's the first on the list alphabetically
with an 'A' in his name*/

$info ber 
/*would grab bertie because he's the first on the list with a ber in the 
beginning of his name, 
and not grab albert who has a ber later in his name and
is ahead of bertie in the array*/

这就是我到目前为止所拥有的。现在,如果我尝试执行$info ber,它将获取Albert,因为它首先遇到数组中的他的名字。我考虑过使用子字符串和charAt,但我找不到一种有效的方法。我也在考虑使用findIndex或indexOf,但不知道如何使用它。

代码语言:javascript
复制
for(let i = 0; i < namelist.length; i++){
 if(namelist[i].includes(name)){
 object = namelist[i];
 console.log(object);
 break;
 }
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-06-22 14:54:40

您可以结合使用find()和startswith()从排序列表中获取第一个匹配项:

​

代码语言:javascript
复制
let namelist = ['adam', 'al', 'albert', 'bertie', 'cole'];

let s = "ber"
let found = namelist.find(item => item.startsWith(s))

console.log(found)

s = 'a'
found = namelist.find(item => item.startsWith(s))

console.log(found)

​

票数 1
EN

Stack Overflow用户

发布于 2019-06-22 14:54:35

您可以结合使用Array.find()和Array.startsWith()来获取以字符串开头的名称。由于用户在搜索时可能使用大写字母,因此在搜索字符串上使用String.toLowerCase()。

​

代码语言:javascript
复制
const namelist = ['adam', 'al', 'albert', 'bertie', 'cole'];

const getName = str => namelist.find(s => s.startsWith(str.toLowerCase()));

console.log(getName('a')); // admin
console.log(getName('ber')) // bertie
console.log(getName('Ber')) // bertie

​

票数 1
EN

Stack Overflow用户

发布于 2019-06-23 01:19:45

这就是我的最终代码,ty ori和mark

代码语言:javascript
复制
            let words = args[0];
            let object = "";
            let temparray = [];
            let found = namearray.find(item => {item.startsWith(args[0])});
                    for(let i = 0; i <= namearray.length; i++){ 
                        if(i < namearray.length && namearray[i].startsWith(words)){
                            object = namearray[i];
                            console.log(object);
                            break;
                        }
                        else if(i < namearray.length && namearray[i].includes(words)){
                            temparray.push(namearray[i]);
                            console.log(temparray);
                        }
                        else if(i >= namearray.length && found === undefined){
                            console.log(temparray[0]);
                            object = temparray[0];
                        }               
                    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56713267

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档