ganesh kaspate
ganesh kaspate

Reputation: 2685

iterate over a map and change the position of element

I have an array of object

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

Here I am using map over here to itertae

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

mapToNA(test)

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

Now I want value which is NA then it should be at the end

so Output would be like:

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

How can I get this ?

Upvotes: 0

Views: 457

Answers (8)

Ori Drori
Ori Drori

Reputation: 191986

You can partition the array to items with type, and items out without, and then map the relevant items' type to NA, and use spread to combine the arrays:

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>

Upvotes: 1

jagannathbhat
jagannathbhat

Reputation: 113

We can use the sort function.

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

Or you can use the shorter one

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

Learn more about the sort method here.

Upvotes: 0

adiga
adiga

Reputation: 35222

You could use 2 separate arrays to keep track of objects with and without type. Merge them after the loop. This is readable and faster.

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

console.log( withType.concat(withoutType) )

You could also reduce with 2 separate arrays and flat them:

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() )

Upvotes: 1

kishore Rajendran
kishore Rajendran

Reputation: 278

You can map the array and then sort your array based on '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)

Upvotes: 0

DecPK
DecPK

Reputation: 25408

You can easily achieve this result using map and a custom sorting algorithm.

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);

Upvotes: 1

dante
dante

Reputation: 1121

Do you want to switch position between last element of array with your target element using Array.prototype.map ? If so,

 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"
*/

only use map method is a bit give you constraints yourself. try use splice or something. using only map has low efficiency

Upvotes: 0

Sifat Haque
Sifat Haque

Reputation: 6057

You can use default sort function from javascript to solve this.

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

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

console.log(arr)

Upvotes: 0

0stone0
0stone0

Reputation: 44009

Since you're already using lodash, lets use _.sortBy with a custom function:

// 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"
  }
]

Upvotes: 2

Related Questions