Rahul shukla
Rahul shukla

Reputation: 378

Sort an array of objects before getting the csv?

I am trying to sort an array before it goes to csv. I am getting an array of array objects i need to sort them.

So that the company and position if n/a those values come after those where company and position is not n/a.

I am sharing the screen shot of complete array and the function help me.

enter image description here

The two arrays one in which company and position name is n/a and one in which it is not before going to csv.

I need to sort them as per where data is n/a that part should come in last.

How can i do that..

I used but it did not worked. please help

var array_length = users.length;
var array_2 = [];
var k = (array_length-1);
for(i=0;i<array_length;i++){
   console.log(k);
   if(users[i]=="n/a") {
      array_2['_'+k]= users[i]
   } else {
      array_2[i]= users[i]
   }
   k--;
}

Upvotes: 0

Views: 61

Answers (2)

Rahul shukla
Rahul shukla

Reputation: 378

I got the solution by sending it in two array and then by merging them in one:-

function sort_(users_arr=false)
{ 
  var complete_member = 0,
       members = users_arr.filter(function(user) { /** here i got complete member**/
            return user.level >= 1
        });
        members.forEach(function(member) {
        if(member.level == 2){
          complete_member++
        }
     });
    var test = [];
    var test1 = [];
    var loop_length = members.length;     
     for (var i = 0; i < loop_length; i++) {
       if(members[i].company == 'n/a' || members[i].position == 'n/a'){
            test1.push(members[i]);
          }
       else{
             test.push(members[i]);
           }
      }   
     var flatArray = [].concat.apply(test,test1);
     return flatArray;  
}

and i called this one in my download csv code:-

Csv download function:-

   Function downloadFile() {
        var level = 1;
        if(onlyComplete === true){
            level = 2;
        }
        DownloadValues(function(downloadFields) {
            downloadFields.push("group");
            var user_subscription = "free";
            var csv_data_length = 600;
            if(user_subscription == "paid")
                csv_data_length = users.length;
            var users_ = sort_(users); /** called sort function **/
    ..........
    }

}

Upvotes: 0

Pranay Rana
Pranay Rana

Reputation: 176956

try apply sort function on your array like this

users.sort(function(a, b) {
  var nameA = a.company.toUpperCase(); // ignore upper and lowercase
  var nameB = b.company.toUpperCase(); // ignore upper and lowercase
  if( nameA === 'N/A' ||  nameB === 'N/A')
    return -1;
  if (nameA < nameB) {
    return -1;
  }
  if (nameA > nameB) {
    return 1;
  }

  // names must be equal
  return 0;
});

Upvotes: 1

Related Questions