gpt4 book ai didi

JavaScript:根据 "outside"参数对数组进行排序

转载 作者:行者123 更新时间:2023-12-01 00:44:36 25 4
gpt4 key购买 nike

在 JavaScript 中,我有一个对象数组和一个输入值,如下所示:

const inputVal = 'foo';

const objArray = [
{title: 'blahaa', type: 'foobar'},
{title: 'foobar', type: 'wohoo'},
{title: 'foobar', type: 'foobar'},
{title: 'foobar', type: 'aaaabaa'},
{title: 'foobar', type: 'moo'},
{title: 'aaah', type: 'foogoo'},
{title: 'foohiii', type: 'foobar'},
{title: 'aaah', type: 'foobar'},
{title: 'foodoo', type: 'aaaabaa'},
{title: 'gaaaaaah', type: 'foobar'},
{title: 'foobar', type: 'foogoo'},
];

如您所见,数组中的所有元素在标题或类型中都具有以“foo”开头的属性。此外,所有元素都是唯一的,相同的标题和/或类型可以出现在多个元素中,但两者的相同组合不能出现两次。

我想按以下方式对该数组进行排序:

  1. 标题和类型均以 inputVal 开头
    1. 按字母顺序输入
    2. 标题按字母顺序排列
  2. 标题以 inputVal 开头,但不是类型
    1. 按字母顺序输入
    2. 标题按字母顺序排列
  3. 类型以 inputVal 开头,但不是标题
    1. 按字母顺序输入
    2. 标题按字母顺序排列

示例列表将按以下方式排序:

const objArray = [
{title: 'foobar', type: 'foobar'}, // Criterium 1
{title: 'foohiii', type: 'foobar'}, // Criterium 1
{title: 'foobar', type: 'foogoo'}, // Criterium 1
{title: 'foobar', type: 'aaaabaa'}, // Criterium 2
{title: 'foodoo', type: 'aaaabaa'}, // Criterium 2
{title: 'foobar', type: 'moo'}, // Criterium 2
{title: 'foobar', type: 'wohoo'}, // Criterium 2
{title: 'aaah', type: 'foobar'}, // Criterium 3
{title: 'blahaa', type: 'foobar'}, // Criterium 3
{title: 'gaaaaaah', type: 'foobar'}, // Criterium 3
{title: 'aaah', type: 'foogoo'}, // Criterium 3
];

我尝试将array.prototype.sort(callback)与几个不同的回调函数一起使用,但我似乎没有得到正确的函数。谁能帮我吗?

最佳答案

您可以更改条件并首先按三组排序,然后按值排序。

const
value = 'foo',
start = (v => s => s.startsWith(v))(value),
array = [{ title: 'blahaa', type: 'foobar' }, { title: 'foobar', type: 'wohoo' }, { title: 'foobar', type: 'foobar' }, { title: 'foobar', type: 'aaaabaa' }, { title: 'foobar', type: 'moo' }, { title: 'aaah', type: 'foogoo' }, { title: 'foohiii', type: 'foobar' }, { title: 'aaah', type: 'foobar' }, { title: 'foodoo', type: 'aaaabaa' }, { title: 'gaaaaaah', type: 'foobar' }, { title: 'foobar', type: 'foogoo' }];

array.sort((a, b) =>
(start(b.title) && start(b.type)) - (start(a.title) && start(a.title))
|| start(b.title) - start(a.title)
|| start(b.type) - start(a.type)
|| a.type.localeCompare(b.type)
|| a.title.localeCompare(b.title)
);

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于JavaScript:根据 "outside"参数对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57493852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com