0

I have here 2 array's

1st array is the main data and 2nd array by property it must be the bases of 1st array data orders.

2nd array sample :

var order_basis = [ 
 { tag:'vip' }, { tag:'home' } { tag:'work' } 
]

1st array data

var main_data = [
{ tag:'work',name:'sample',contact:'0987654',email:'sample@email.com' },
{ tag:'home',name:'sample',contact:'0987654',email:'sample@email.com' },
{ tag:'home',name:'sample',contact:'0987654',email:'sample@email.com' },
{ tag:'work',name:'sample',contact:'0987654',email:'sample@email.com' },
{ tag:'vip',name:'sample',contact:'0987654',email:'sample@email.com' }, 
]

expected output is

base on the 2nd array tag order it must be ..

ReOrder( main_data  ,order_basis ){

//main code   

  return 
}

result is

tag:'vip' name:'sample' contact:'0987654' email:'sample@email.com'
tag:'home' name:'sample' contact:'0987654' email:'sample@email.com'
tag:'home' name:'sample' contact:'0987654' email:'sample@email.com'
tag:'work' name:'sample' contact:'0987654' email:'sample@email.com' 
tag:'work' name:'sample' contact:'0987654' email:'sample@email.com'

Thank you for helping mate! ..

Jakegarbo
  • 1,201
  • 10
  • 20

2 Answers2

1

You could take the index of the tags of order_basis assortorder by using an object with this data.

var order_basis = [{ tag: 'vip' }, { tag: 'home' }, { tag: 'work' }],
    main_data = [{ tag: 'work', name: 'sample', contact: '0987654', email: 'sample@email.com' }, { tag: 'home', name: 'sample', contact: '0987654', email: 'sample@email.com' }, { tag: 'home', name: 'sample', contact: '0987654', email: 'sample@email.com' }, { tag: 'work', name: 'sample', contact: '0987654', email: 'sample@email.com' }, { tag: 'vip', name: 'sample', contact: '0987654', email: 'sample@email.com' }],
    order = {};

order_basis.forEach(function (o, i) { order[o.tag] = i + 1 });

main_data.sort(function (a, b) {
    return order[a.tag] - order[b.tag];
});

console.log(main_data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can sort the main function based on the order_basis array.

function getFormatted(main, order_basis){
  order_basis = order_basis.map(x => x.tag);
  return main.sort(function(a, b){
    if(order_basis.indexOf(a.tag) > order_basis.indexOf(b.tag))
      return 1;
    return -1;
  });
}

var order_basis = [{ tag: 'vip' }, { tag: 'home' }, { tag: 'work' }],
main_data = [{ tag: 'work', name: 'sample', contact: '0987654', email: 'sample@email.com' }, { tag: 'home', name: 'sample', contact: '0987654', email: 'sample@email.com' }, { tag: 'home', name: 'sample', contact: '0987654', email: 'sample@email.com' }, { tag: 'work', name: 'sample', contact: '0987654', email: 'sample@email.com' }, { tag: 'vip', name: 'sample', contact: '0987654', email: 'sample@email.com' }];


console.log(getFormatted(main_data, order_basis));
.as-console-wrapper { max-height: 100% !important; top: 0; }
void
  • 36,090
  • 8
  • 62
  • 107