迭代地图并更改元素的位置

iterate over a map and change the position of element

我有一个对象数组

const test = [{'type':'Material'}, {'type':''}, {'type':'ABC'}]

这里我用的是map over here to itertae

export const mapToNA = values => map(test, value => type || 'NA')

mapToNA(test)

本returns本[{'type':'Material'}, {'type':'NA'}, {'type':'ABC'}]

现在我想要的值是 NA 那么它应该在最后

所以输出会是这样的:

[{'type':'Material'},{'type':'ABC'},{'type':'NA'}, ]

我怎样才能得到这个?

由于您已经在使用 lodash,让我们使用 _.sortBy 和自定义函数:

// Data
let test = [{'type':'Material'}, {'type':''}, {'type':'ABC'}];

// Map '' to 'NA'
const mapToNA = values => _.map(test, value => { return { type: value.type || 'NA' }; } )
test = mapToNA(test)

// Sort
test = _.sortBy(test, element => (element.type === 'NA'));

// Log
console.log(test)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

[
  {
    "type": "Material"
  },
  {
    "type": "ABC"
  },
  {
    "type": "NA"
  }
]

您可以使用 javascript 中的默认 sort 函数来解决此问题。

const arr =[{'type':'Material'}, {'type':'NA'}, {'type':'ABC'}];

arr.sort((a, b) => a["type"] === 'NA' ? 1 : -1);

console.log(arr)

您可以使用 map 和自定义排序算法轻松实现此结果。

const test = [
  { type: "ABC" },
  { type: "Material" },
  { type: "" },
  { type: "ABC" },
  { type: "" },
];
const result = test
  .map((s) => (s.type === "" ? { type: "NA" } : s))
  .sort((a, b) => {
    if (a.type === "NA" && b.type === "NA") return 0;
    if (a.type === "NA") return 1;
    if (b.type === "NA") return -1;
    else return 0;
  });
console.log(result);

是否要使用 Array.prototype.map 在数组的最后一个元素与目标元素之间切换位置? 如果是这样,

 const test = [{"type": "Material"}, {"type": "NA"}, {"type":"ABC"}];

const someFunction = values => {
   // NAIndex remember which index of values have "NA" 
   let NAIndex = 0;
   // copy original array values.
   const copiedValues = values.slice();
   return values.map((value,index) => {
    
   if(value["type"] === "NA"){
     NAIndex = index;
     return copiedValues[values.length-1];
   }
   else if(index === values.length-1){
     return copiedValues[NAIndex];
   }
   return value;
})
}

const array = someFunction(test);
console.log(array)

/*
(3) [Object, Object, Object]
0: Object
type: "Material"
1: Object
type: "ABC"
2: Object
type: "NA"
*/

只用map方法有点给自己束缚了。尝试使用拼接或其他东西。只用map效率低

您可以 map 阵列,然后 sort 您的阵列基于 'NA'

const test = [{'type':'Material'}, {'type':''}, {'type':'ABC'}]

let result = test
  .map(val => ({type: val.type || 'NA'}))
  .sort((a,b) => a.type === 'NA' ? 1 : b.type === 'NA' ? -1 : 0);

console.log(result)

您可以使用 2 个单独的数组来跟踪有无 type 的对象。循环后合并它们。这是可读的和更快的。

const withType = [],
      withoutType = []
      
for (const o of test) {
  if (o.type)
    withType.push(o)
  else
    withoutType.push({ type: 'NA' })
}

console.log( withType.concat(withoutType) )

您还可以 reduce 使用 2 个单独的数组和 flat 它们:

const group = test.reduce((acc, o) => {
  if (o.type)
    acc[0].push(o)
  else
    acc[1].push({ 'type': 'NA' })
  return acc
}, [[], []])

console.log( group.flat() )

我们可以使用sort函数。

test.sort((elem1, elem2) => {
    if (elem2.type !== 'NA')
            if (elem1.type === 'NA')
                    return 1
            else
                    return 0
    return -1
})

或者您可以使用较短的

test.sort((elem1, elem2) =>
    elem2.type !== 'NA' ? elem1.type === 'NA' ? 1 : 0 : -1)

详细了解排序方法here

你可以将数组划分为有类型的项和无类型的项,然后将相关项的类型映射到 NA,并使用 spread 组合数组:

const data = [{'type':'Material'}, {'type':''}, {'type':'ABC'}];

// Pertition items to have type and NA
const [itemsWithType, itemsWithEmptyType] = _.partition(data, o => o.type)

// map the itemsWithEmptyType to NA and combine
const result = [...itemsWithType, ...itemsWithEmptyType.map(o => ({ ...o, type: 'NA' }))]

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>