1

Lets say I have a base array

let object2 = ["DotNet", "ETL", "Hadoop", "Java", "Oracle", "Pega", "MainFrame"]

I want to order this second array in the same order of the base array

 let object1 = [{Name: "Java", ResourceCount: 3}, {Name: "DotNet", ResourceCount: 4}, {Name: "Hadoop", ResourceCount: 1}, {Name: "Pega", ResourceCount: 2}, {Name: "Oracle", ResourceCount: 1}, {Name: "ETL", ResourceCount: 1}, {Name: "MainFrame", ResourceCount: 0}]

So it looks like this

object1 = 
[{Name: "DotNet", ResourceCount: 4},
{Name: "ETL", ResourceCount: 1},
{Name: "Hadoop", ResourceCount: 1},
{Name: "Java", ResourceCount: 3}, 
{Name: "Oracle", ResourceCount: 1},
{Name: "Pega", ResourceCount: 2},
{Name: "MainFrame", ResourceCount: 0}]

how can I do that without hardcoding?

GalAbra
  • 5,048
  • 4
  • 23
  • 42
Terrance Jackson
  • 606
  • 3
  • 13
  • 40
  • Iterate over object2 and filter all the objects of objects2 by Name to create a new array in this order. – Frank Adrian Oct 29 '19 at 17:46
  • You can also look at, [`How to sort an array of objects with labels according to other array of labels?`](https://stackoverflow.com/questions/58606533/how-to-sort-an-array-of-objects-with-labels-according-to-other-array-of-labels/58606607#58606607) – Code Maniac Oct 29 '19 at 17:50

2 Answers2

1

A possible solution would be to use Array.map in order to iterate your ordered names list - and "map" each String into the correlating object in your objects list.

The correlation is done using Array.find, which receives as a parameter a function that returns the relevant object:

const list1 = ["DotNet", "ETL", "Hadoop", "Java", "Oracle", "Pega", "MainFrame"];
const list2 = [{Name: "Java", ResourceCount: 3}, {Name: "DotNet", ResourceCount: 4}, {Name: "Hadoop", ResourceCount: 1}, {Name: "Pega", ResourceCount: 2}, {Name: "Oracle", ResourceCount: 1}, {Name: "ETL", ResourceCount: 1}, {Name: "MainFrame", ResourceCount: 0}];

const ordered = list1.map(function(nameValue) {
  return list2.find((obj) => (obj.Name === nameValue));
});

console.log(ordered);
GalAbra
  • 5,048
  • 4
  • 23
  • 42
0

let object2 = ["DotNet", "ETL", "Hadoop", "Java", "Oracle", "Pega", "Mainframe"]
let object1 = [{Name: "Java", ResourceCount: 3}, {Name: "DotNet", ResourceCount: 4}, {Name: "Hadoop", ResourceCount: 1}, {Name: "Pega", ResourceCount: 2}, {Name: "Oracle", ResourceCount: 1}, {Name: "ETL", ResourceCount: 1}, {Name: "Mainframe", ResourceCount: 0}]
var arr=[]

object2.map(item=>{
  object1.map(data=>{
    if(data.Name===item)
         {
           arr.push(data)
         }          
                    })
})
console.log(arr)
Ayushi Keshri
  • 680
  • 7
  • 18