Javascript 根据数组元素的值对数组元素进行排序
我有以下对象数组:Javascript 根据数组元素的值对数组元素进行排序,javascript,arrays,sorting,Javascript,Arrays,Sorting,我有以下对象数组: [ 0: { id: 1, type: 'input' }, 1: { id: 2, type: 'boolean' }, 2: { id: 3, type: 'choice' }, 3: { id: 1, type: 'select' }, ] 我想根据type的值对数组元素进行排序。如果type是'choice',我想将元素放在数组的最后一个位置,即第
[
0: {
id: 1,
type: 'input'
},
1: {
id: 2,
type: 'boolean'
},
2: {
id: 3,
type: 'choice'
},
3: {
id: 1,
type: 'select'
},
]
我想根据type的值对数组元素进行排序。如果type是'choice',我想将元素放在数组的最后一个位置,即第四个位置。如果类型为“boolean”,则将其置于第三位。如果类型为“选择”,则将其放在第二位
我知道如何用数值对数组排序
arr.sort((a, b) => {
if (a.type < b.type) return -1
return a.type > b.type ? 1 : 0
})
arr.sort((a,b)=>{
if(a.typeb.type?1:0
})
我在比较属性值和排序时遇到问题
请帮帮我。我们将非常感谢您的帮助
关于,通常,如果需要根据对象的某些字符串属性对数组进行排序,则需要创建另一个表示排序顺序的数组。然后使用
indexOf
并减去索引
const order=['input','select','boolean','choice'];
常数arr=[
{
id:1,
类型:“输入”
},
{
id:2,
类型:“布尔”
},
{
id:3,
类型:“选择”
},
{
id:1,
键入:“选择”
},
]
arr.sort((a,b)=>order.indexOf(a.type)-order.indexOf(b.type));
console.log(arr)
如果您有
const arr = [
{
id: 1,
type: 'input',
val: 1
},
{
id: 2,
type: 'boolean',
val: 3
},
{
id: 3,
type: 'choice',
val: 4,
},
{
id: 1,
type: 'select',
val: 2
},
]
这样就很容易了:只需arr.sort((a,b)=>a.val-b.val)
由于您没有属性val
,因此可以在以下操作之前将其设置为启用:
const typeToValue = {
input: 1,
boolean: 3,
choice: 4,
select: 2
}
arr.forEach(el => {
el.val = typeToValue[el.type]
})
arr.sort((a, b) => a.val - b.val)
也许您不想弄脏元素,请注意el.val==typeToValue[el.type]
意思是你可以写作
arr.sort((a,b)=>typeToValue[a.type]-typeToValue[b.type])
最后,如果您有一个排序数组['input','select','boolean','choice']
,您可以通过array.prototype.reduce将其转换为typeToValue
对象
const orders = ['input', 'select', 'boolean', 'choice']
const typeToValue = orders.reduce((o, el, i) => (o[el] = i, o), {})
或者如果您不喜欢使用Object.fromEntries减少
const typeToValue = Object.fromEntries(orders.map((el, i) => [el, i]))
const arr=[{“id”:1,“type”:“input”},{“id”:2,“type”:“boolean”},{“id”:3,“type”:“choice”},{“id”:1,“type”:“select”}]
const orders=['input','select','boolean','choice']
const typeToValue1=orders.reduce((o,el,i)=>(o[el]=i,o),{})
const typeToValue2=Object.fromEntries(orders.map((el,i)=>[el,i]))
//只需切片即可复制数组,因为排序已就位
log(arr.slice(0).sort((a,b)=>typeToValue1[a.type]-typeToValue1[b.type]))
log(arr.slice(0).sort((a,b)=>typeToValue2[a.type]-typeToValue2[b.type])
考虑一个单独的数组,该数组按所需顺序保存类型,并根据它们在该数组中的索引进行排序。或者有类型和位置的hashmap。嗯,没有name
属性…谢谢您的详细回答。:)欢迎您@SujanShrestha:)