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?

2

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.