Home > Software design >  How to change sequence of old array according to new array
How to change sequence of old array according to new array

Time:08-04

I have a existing array, and now I want to change the sequence of old array according to new array's key

// Existing Array
var data = [
    {
        name: 'section-intro', 
        children: ['service-addressBox', 'service-banner']
    },
    {name: 'section-breadcrumb', children: ['h', 'i', 'j']},
    {name: 'section-products', children: []},
    {name: 'section-about', children: []},
    {name: 'section-timeline', children: []},
    {name: 'section-nearbyOutlets', children: []}
]


// New Array
['section-nearbyOutlets', 'section-intro', 'section-products', 'section-breadcrumb', 'section-timeline', 'section-about']

CodePudding user response:

If the two arrays have the same number of elements (or if you only are interested in the elements appearing in the new one) you can try something like this using map:

// Existing Array
const data = [
  {
    name: 'section-intro',
    children: ['service-addressBox', 'service-banner']
  },
  { name: 'section-breadcrumb', children: ['h', 'i', 'j'] },
  { name: 'section-products', children: [] },
  { name: 'section-about', children: [] },
  { name: 'section-timeline', children: [] },
  { name: 'section-nearbyOutlets', children: [] }
]

// New Array
const newArray = ['section-nearbyOutlets', 'section-intro', 'section-products', 'section-breadcrumb', 'section-timeline', 'section-about']

const orderedArray = newArray.map(element => data.find(originalElement => originalElement.name === element))

console.log(JSON.stringify(orderedArray, null, 2))

Here we create a new array (orderedArray) but you can also overwrite one of the existing two if you prefer to.

CodePudding user response:

You can accomplish by manually sorting by name

var temp=[]
for(let name :newarray){
   for(let datum:data){
     if(datum.name==name)
       temp.append(datum)
     }
   }
data=temp

CodePudding user response:

If we're talking about ordering, than you can use Array.sort

// Existing Array
let data = [
    {
        name: 'section-intro', 
        children: ['service-addressBox', 'service-banner']
    },
    {name: 'section-breadcrumb', children: ['h', 'i', 'j']},
    {name: 'section-products', children: []},
    {name: 'section-about', children: []},
    {name: 'section-timeline', children: []},
    {name: 'section-nearbyOutlets', children: []}
]
// New Array
const order = ['section-nearbyOutlets', 'section-intro',
  'section-products', 'section-breadcrumb', 'section-timeline', 'section-about']

data = data.sort((a, b) => {
  const ixa = order.indexOf(a.name)
  const ixb = order.indexOf(b.name)
  return ixa < ixb ? -1 : 1
})

console.log(data)

  • Related