我需要一些帮助来移动对象数组中的位置索引。我有一堆对象数组,它们需要根据value key在索引0或1处进行移位。
const arrayObj1 = [
{
id: 234,
value: "FGH"
},
{
id: 454,
value: "XYZ"
},
{
id: 654,
value: "ABC"
},
{
id: 543,
value: "ABC"
},
]假设我有上面的对象数组,如果值为"ABC",我想将位置移动到索引0,1。到目前为止,它们的位置在索引2和3。因此,对象的数组在移动位置后将如下所示。
expectedArrayofObj = [
{
id: 654,
value: "ABC"
},
{
id: 543,
value: "ABC"
},
{
id: 234,
value: "FGH"
},
{
id: 454,
value: "XYZ"
},
]发布于 2020-12-23 13:14:09
const arrayObj1 = [
{
id: 234,
value: 'FGH',
},
{
id: 454,
value: 'XYZ',
},
{
id: 654,
value: 'ABC',
},
{
id: 543,
value: 'ABC',
},
]
const shift = (arr, value) => {
const newArr = []
// Pushing ABC first
for (const obj of arr) {
if (obj.value === value) {
newArr.push(obj)
}
}
// Pushing the rest
for (const obj of arr) {
if (obj.value !== value) {
newArr.push(obj)
}
}
return newArr
}
console.log(shift(arrayObj1, 'ABC'))
如果你不关心其他元素的顺序,你可以使用(不稳定的)排序:
const arrayObj1 = [
{
id: 234,
value: 'FGH',
},
{
id: 454,
value: 'XYZ',
},
{
id: 654,
value: 'ABC',
},
{
id: 543,
value: 'ABC',
},
]
const shift = (arr, value) => {
const sortingFunction = (a, _) => (a.value === value ? -1 : +1)
arrayObj1.sort(sortingFunction)
return arrayObj1
}
console.log(shift(arrayObj1, 'ABC'))
发布于 2020-12-23 13:18:30
const arrayObj1 = [
{
id: 234,
value: 'FGH',
},
{
id: 454,
value: 'XYZ',
},
{
id: 654,
value: 'ABC',
},
{
id: 543,
value: 'ABC',
},
]
index = arrayObj1 .findIndex(resp => resp.value=='ABC')
arrayObj1 .push(...arrayObj1 .splice(0, index));
console.log(arrayObj1)
发布于 2020-12-23 20:48:15
const arrayObj1 = [{id: 234, value: "FGH"},{id: 454,value: "XYZ"},{id: 654,value: "ABC"},{id: 543,value: "ABC"}];
function shiftBy(value) {
return arrayObj1.reduce((arr, c) => ((c.value===value && [c, ...arr]) || [...arr, c]),[]);
}
console.log(shiftBy("ABC"));
https://stackoverflow.com/questions/65419309
复制相似问题