Home > OS >  Javascript select and reorder elements in an array
Javascript select and reorder elements in an array

Time:04-28

I have a data array like this:

dataArray = [
0: {"Item1" : Val1, "Item2" : Val2, "Item3" : Val3 ... "ItemN" : ValN}
1: {"Item1" : Val1, "Item2" : Val2, "Item3" : Val3 ... "ItemN" : ValN}
.
.
N: {"Item1" : Val1, "Item2" : Val2, "Item3" : Val3 ... "ItemN" : ValN}
]

I have another array which contains a set of arbitrary, variable elements in a desired order:

selArray = ["Item2", "Item9", "Item7"]

The desired output:

outArray = [
0: {"Item2" : Val2, "Item9" : Val9, "Item7" : Val7}
1: {"Item2" : Val2, "Item9" : Val9, "Item7" : Val7}
.
.
N: {"Item2" : Val2, "Item9" : Val9, "Item7" : Val7}
]

I want to select and reorder the elements in dataArray based on the elements in selArray. The contents of both dataArray and selAarray are going to change multiple times in the application, so the selecting on position in the array, or deleting items in the array won't work.

Would appreciate any ideas about how to do this. TIA

CodePudding user response:

Something like this ought to do you:

function selectProperties( arr, ...keys ) {
  const selection = arr.map( obj =>
    Object.fromEntries(
      Object
      .entries(obj)
      .filter( tuple => arr.includes(tuple[0]) )
    )
  )
}

But it's probably easier just to use Lodash.js and...

const _ = require('lodash');

const selectProperties = ( arr, ...keys ) => arr.map( obj =>
  _.pick(obj,keys)
);

Code you don't write is code you don't have to maintain.

CodePudding user response:

I hope it helps you.

const dataArray = [{
    "Item5": 5,
    "Item6": 6,
    "Item1": 1,
    "Item2": 2,
    "Item3": 3,
    "Item4": 4,
  }, {
    "Item5": 5,
    "Item6": 6,
    "Item1": 1,
    "Item3": 3,
    "Item2": 2,
    "Item4": 4,
  }

]

const selArray = ["Item1", "Item2", "Item3", "Item4", "Item5", "Item6"]

const organized = dataArray.map((elm) => {
  nelm = {};
  selArray.map((elm2) => {
    if (elm.hasOwnProperty(elm2)) {
      return nelm[elm2] = elm[elm2]
    }
  })
  return nelm
})

console.log(organized)

CodePudding user response:

Thanks for the suggestions. My brute force solution is to

  1. convert the data array to an object
  2. filter and reduce the object
  3. reorder the object elements into an array based on selArr:
var inMap = { ...inData }
var outData = [];
for(i = 0; i < inData.length; i  ){
  var tmp2 = Object.keys(inMap[i]).
  filter((key) => selArr.includes(key)).
  reduce((cur, key) => { return Object.assign(cur, { [key]: inMap[i][key] })}, {});

  var tmp3 = [];
  for(j = 0; j < selArr.length;j  ){
     tmp3[selArr[j]] = tmp2[selArr[j]];
  }
 outData.push(tmp3);
}

This works for the different cases I need to use. AB

  • Related