-3

I'm having a sample object. I need to re arrange the objects a according to "Technology" key value. The array should be arranged in this way,

  • if("Technology" == "SharePoint") these items should come first.
  • if("Technology" == "Sql Server") these items should come second
  • if("Technology" == "JAVA") these items should come third

var dataArray = [{    
    "EmployeeName": "John",    
    "Experience": "12",    
    "Technology": "SharePoint"    
}, {    
    "EmployeeName": "Charles",    
    "Experience": "9",    
    "Technology": "Sql Server"    
}, {    
    "EmployeeName": "Tommy",    
    "Experience": "3",    
    "Technology": "JAVA"    
}, {    
    "EmployeeName": "Daine",    
    "Experience": "7",    
    "Technology": "Sql Server"    
}, {    
    "EmployeeName": "Roger",    
    "Experience": "6",    
    "Technology": "JAVA"    
},
{    
    "EmployeeName": "John",    
    "Experience": "12",    
    "Technology": "SharePoint"    
}, {    
    "EmployeeName": "Michel",    
    "Experience": "9",    
    "Technology": "Sql Server"    
}, {    
    "EmployeeName": "Jo",    
    "Experience": "3",    
    "Technology": "SharePoint"    
}, {    
    "EmployeeName": "Jhona",    
    "Experience": "7",    
    "Technology": "JAVA"    
}, {    
    "EmployeeName": "Toba",    
    "Experience": "6",    
    "Technology": "SharePoint"    
}];
jabaa
  • 5,844
  • 3
  • 9
  • 30
  • 1
    JSON tag: _"Do not use this tag for native JavaScript objects or JavaScript object literals."_ [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation). There is no JSON in this question. – jabaa Oct 04 '21 at 13:28

1 Answers1

0

Use Array.sort

const order = ["SharePoint", "Sql Server", "JAVA"];
const dataArray = [{"EmployeeName":"John","Experience":"12","Technology":"SharePoint"},{"EmployeeName":"Charles","Experience":"9","Technology":"Sql Server"},{"EmployeeName":"Tommy","Experience":"3","Technology":"JAVA"},{"EmployeeName":"Daine","Experience":"7","Technology":"Sql Server"},{"EmployeeName":"Roger","Experience":"6","Technology":"JAVA"},{"EmployeeName":"John","Experience":"12","Technology":"SharePoint"},{"EmployeeName":"Michel","Experience":"9","Technology":"Sql Server"},{"EmployeeName":"Jo","Experience":"3","Technology":"SharePoint"},{"EmployeeName":"Jhona","Experience":"7","Technology":"JAVA"},{"EmployeeName":"Toba","Experience":"6","Technology":"SharePoint"}];
const output = dataArray.sort((a, b) => {
  if (order.indexOf(a.Technology) > order.indexOf(b.Technology)) return 1;
  else if (order.indexOf(a.Technology) < order.indexOf(b.Technology)) return -1;
  else return 0;
});
console.log(output)
Nitheesh
  • 19,238
  • 3
  • 22
  • 49