2

I am making a MEAN Stack application, and am attempting to create a database of businesses- which requires an empty array to push new instances of the Business model into.

I then want to sort the index of the businesses based on two of the keys- "name" (alphabetically) and "upVotes".

Here is what I have in my business.service file (client side):

var service = {
  create: create,
  businesses: [],
  upVote: upVote,
  showAllBiz: showAllBiz,

};
function showAllBiz(){
  $http.get("/api/businesses")
  .then(function(res) {
    service.businesses = res.data;
  }, function(err) {
      $log.info(err);
  });
}
 function create(data) {
  return $http({
    method: 'POST',
    url:    '/api/businesses',
    data:   data,
    headers: {
      'Content-Type': 'application/json'
    }
  }).then(function(res) {
      service.businesses.push(res.data);
  });
}

I also tried to sort() on the back end, with no results. Here is what that looks like:

var Business    = require("../models/business");
var nodemailer  = require("nodemailer");
var transporter = nodemailer.createTransport();
var firstBy     = require("thenby");

function index(req, res) {
 if(req.query.search){
  Business.find({}).then(function(data) {
  var reg = new RegExp(req.query.search, "i");
  data = data.filter(function(biz) {
    if(reg.test(biz.name)) return biz
  })

  res.json(data);
  }, function(err) {
  res.json(err);
 });
 } else{
  Business.find({}).then(function(data) {
   res.json(data);
   }, function(err) {
   res.json(err);
  });
 }
}


function create(req, res) {
var business       = new Business();  

console.log(req.body);
business.name              = req.body.name;
business.address1          = req.body.address1;
business.address2          = req.body.address2;
business.email             = req.body.email;
business.twitterHandle     = req.body.twitterHandle;
business.upVote            = req.body.upVote;

business.save(function(err, savedBusiness) {
 if (err) {
  res.send(err)
 }

 res.json(savedBusiness);
});

I am getting stuck on the fact that I need the empty array for the new instances (in my services), but I also need to make use of the objects within the array in the .sort() method to access the keys (which I would like to sort).

I played with Teun's thenBy.js but was a bit out of my depth.

I have googled sorting arrays and arrays of objects, but these are all examples of sorting information that exists, not information that does not yet exist, thus necessitating the empty array.

2
  • :-). In case you're not aware, editors will sometimes read a post and trim non-essential parts of it, and/or make it more readable. There wasn't much to fix here! Commented Apr 26, 2016 at 21:49
  • 1
    sweet! thanks for the info :-) Commented Apr 26, 2016 at 21:50

1 Answer 1

1

Assuming I understand the question, here's the gist of it with some made up data. I left the sort function a bit more verbose to (hopefully) increase readability.

Note that in the sorter method we are comparing first name, then upVotes, then only returning 0 afterwards to signify object equality. Since we are comparing name first followed by upVotes, this is the equivalent of sorting by name, then upVotes.

let arr = [
    { id: 1, name: 'Dominos', upVotes: 21 },
    { id: 2, name: 'Pizza Hut', upVotes: 31 },
    { id: 3, name: 'Pizza Hut', upVotes: 35 },
    { id: 4, name: 'Dominos', upVotes: 61 },
    { id: 5, name: 'Dominos', upVotes: 2 },
    { id: 6, name: 'Pizza Hut', upVotes: 25 },
    { id: 7, name: 'Dominos', upVotes: 10 },
    { id: 8, name: 'Pizza Hut', upVotes: 3 }
];

function sorter(a, b) {
    if (a.name > b.name)
        return 1;
    if (a.name < b.name)
        return -1;
    if (a.upVotes > b.upVotes)
        return 1;
    if (a.upVotes < b.upVotes)
        return -1;
    return 0;
}

arr.sort(sorter);

console.log(arr);
/* [ { id: 7, name: 'Dominos', upVotes: 2 },
     { id: 8, name: 'Dominos', upVotes: 10 },
     { id: 5, name: 'Dominos', upVotes: 21 },
     { id: 6, name: 'Dominos', upVotes: 61 },
     { id: 4, name: 'Pizza Hut', upVotes: 3 },
     { id: 3, name: 'Pizza Hut', upVotes: 25 },
     { id: 1, name: 'Pizza Hut', upVotes: 31 },
     { id: 2, name: 'Pizza Hut', upVotes: 35 } ] */

[].sort(sorter); // no errors. if the array is empty, the callback will never be run.
Sign up to request clarification or add additional context in comments.

6 Comments

brilliant! @dvlsg this works with the array with fabricated data. it is console logged in the appropriate order. now I want to implement this for the service.businesses (the empty array that the created businesses are pushed into) but end up with an empty array. this is the part I am unclear on- how do i order the array in which data has not been created for?
I might need some additional clarification -- are you concerned about errors being thrown when you attempt to sort an empty array, or are you concerned about situations where specific keys (name, upVotes) are still undefined? Might help to see an exact example of what you expect to be in service.businesses at the time it needs to be sorted.
the model for businesses is var businessSchema = new mongoose.Schema({ name: { type: String }, address1: { type: String }, address2: { type: String }, email: { type: String, required: false }, twitterHandle: { type: String, required: false }, upVote: { type: Number, default: 0 }, upVoters: [{type: String}] }); so the service.businesses will contain the new businesses that are added to the database with those keys.
I'm still a bit lost. The sorter I provided will work as-is if you wanted to sort in memory, whether or not it is empty, and either on the server or the client. If you wanted to sort in the database (which I recommend over javascript sorts, if possible), you should look into using sort of the server flavor. Here are the docs for $sort in mongodb, and here are the docs for mongoose. You'd attach it with Business.find({}).sort({ /* ... */ })
fantastic. thank you @dvlsg. I am using this on the memory side and getting some results!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.