Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import and use _.sortBy from lodash

I'm trying to use _.sortBy method from lodash by making a code like this :

import _sortBy from 'lodash';
var questions = [.......some array....];
questions = _sortBy(questions, 'position');

console.log(questions);

The content of console.log(question) is empty. I don't know why, I think I don't know how to load _.sortBy from lodash. I have tried this :

questions = _sortBy._.sortBy(questions, 'position')

or

questions = _.sortBy(questions, 'position')

But there is an error "bundle.js:45504 Uncaught TypeError: Cannot read property 'sortBy' of undefined" or "Uncaught TypeError: (0 , _jquery2.default)(...).sortable is not a function". Also I have read this page : https://lodash.com/docs#sortBy

But I have no idea how to load and use this _.sortBy method. Please help..:)

Note: Sorry for the stupid question if this question is so easy

like image 674
Maryadi Poipo Avatar asked Aug 09 '16 07:08

Maryadi Poipo


2 Answers

In your case, you have two options :

  • you can import the entire collection : import _ from 'lodash'; Then you will be able to use it like this : _.sortBy()

  • However, you can also import specific function. So rather import whole lodash collection, it's better just import lodash's function, especially when you work in production.

So you can do : import sortBy from 'lodash/sortBy';

Then you will be able to use it like this : sortBy()

like image 147
Paul Boutes Avatar answered Sep 27 '22 20:09

Paul Boutes


you can import specific item using curly braces.

how it works ?

_ is not exported as default so using like below will throw error.

import _ from lodash

however you can import everything from lodash in _ using below code

import * as _ from 'lodash';

but if you want to import specific functions or anything which is exported you can use it like below example

import {sortBy} from 'lodash';

var users = [
  { 'user': 'fred',   'age': 48 },
  { 'user': 'barney', 'age': 36 },
  { 'user': 'fred',   'age': 40 },
  { 'user': 'barney', 'age': 34 }
];

sortBy(users, function(o) { return o.user; });
like image 21
abhirathore2006 Avatar answered Sep 27 '22 21:09

abhirathore2006