Search code snippets, questions, articles...

lodash code snippets

Lodash - Check if a number is within the Range(without if-else)
const number = 10
const start_range = 5;
const end_range = 20;

const num_in_range = _.inRange(number, start_range, end_range);

if (num_in_range) {
    console.log("Number is within the range");
} else {
    console.log("Nomber is not in range");
}
Lodash - Get random number between two numbers
// Get random number between two numbers
const random_number = _.random(1, 100);

console.log(random_number);
Lodash - Get current timestamp in milliseconds
const timestamp = _.now();

console.log(timestamp);
Lodash - merge two arrays and remove duplicates from it
const arr1 = [10, 20, 30, 40];
const arr2 = [20, 30, 50, 60, 70];
const arr3 = [50, 70, 80, 90, 100];

const result = _.union(arr1, arr2, arr3);

console.log(result);
Lodash - object keys conversion to lowercase
let person = {
    "Name": "Richard",
    "Company": "Pied Pieper",
    "Algo Name": "Compression"
};

var result_obj = _.transform(person, function (result, val, key) {
    result[key.toLowerCase()] = val;
});

console.log(result_obj);
Lodash - Get the last element of an array
const items = [10, 20, 30, 40, 50];
const last_item = _.last(items);
// => 50
Lodash - Create a string from array elements join with some separator
const arr = ["This", "is", "Programming", "world"];

// Join using -
const str = _.join(arr, '-');
// => This-is-Programming-world

// Join using space
const str_2 = _.join(arr, ' ');
// => This is Programming world
_.intersectionBy method in Lodash
const result1 = _.intersectionBy([2.8, 1.2], [2.3, 3.4], Math.floor);
console.log(result1);
Lodash - Get common values from multiple arrays
const arr1 = [10, 20, 30];
const arr2 = [5, 20, 40, 30];

const result1 = _.intersection(arr1, arr2);
// => [20,30]

const arr3 = [20];
const result2 = _.intersection(arr1, arr2, arr3);
// => [20]
Lodash - Get all elements of array except the last one
const arr = [10, 20, 30, 40, 50];

const result = _.initial(arr);
// => [10,20,30,40]
Lodash - Get index of first occurence of an array value
const names = ["Ankit", "Rick", "Maggie", "John", "Wick", "Rick", "Carol", "Maggie"];

//Get index of Rick
const rick_index = _.indexOf(names, 'Rick');
// => 1

//Get Index of Maggie start from - 3
const maggie_index = _.indexOf(names, 'Maggie', 3);
// => 7

//Get Index of Maggie start from - 1
const maggie_index_1 = _.indexOf(names, 'Maggie', 1);
// => 2
Lodash - get the first element from an array
const arr = [10, 20, 30, 40, 50];
const first_item = _.head(arr);
// => 10
Lodash - Convert paired Array to key value paired object
const subject = [
    ['name', 'Math'], 
    ['score', 90],
    ['dept', 'Mathematics']
];
const subject_obj = _.fromPairs(subject);
// => { "name": "Math", "score": 90, "dept": "Mathematics"}
Lodash - Flatten an array to a fixed depth
const arr = [
    [10], [20, 30, [40, [50]]], 60, [70, [80]]
];

//Flatten to 1 level
const result_1 = _.flattenDepth(arr, 1);
// => [10,20,30,[40,[50]],60,70,[80]]

//Flatten to 2 level
const result_2 = _.flattenDepth(arr, 2);
// => [10,20,30,40,[50],60,70,80]
Lodash - Flatten an array to multi levels deep
const arr = [10, [12, [15, 16]], [12, [30, [40]], 50]];
const result = _.flattenDeep(arr);

console.log(result);
// => [10,12,15,16,12,30,40,50]
Lodash - Flatten an array to single level deep
const arr = _.flatten([[10], [20, [33, [40]], 50]]);
console.log(arr);
// => [10,20,[33,[40]],50]
Lodash - Find item index from array by searching from the end
var subjects = [
    { 'name': 'Math', 'score': 70 },
    { 'name': 'Physics', 'score': 80 },
    { 'name': 'Chemistry', 'score': 80 },
    { 'name': 'English', 'score': 90 }
];

//It starts searching items from end
// Find index where subject name is Chemistry
const physics_index = _.findLastIndex(subjects, function (item) {
    return item.name == 'Physics'; 
});
console.log("Physics index is : " + physics_index);
// => 1

//Find Index where score is 80
const score_index = _.findLastIndex(subjects, ['score', 80]);
console.log(score_index);
//=> 2
Lodash - Get index of array item based on some condition
const users = [
    { 'user': 'John Deo', 'active': false },
    { 'user': 'Rick Grimes', 'active': false },
    { 'user': 'Negan', 'active': true }
];

//Find Index where user is - Rick Grimes
const index = _.findIndex(users, function (item) {
    return item.user == 'Rick Grimes';
});
console.log("User index is : " + index)
// => 1

// Find item index using full object match
const index_2 = _.findIndex(users, { 'user': 'Negan', 'active': true });
console.log("Object index is : " + index_2);
// => 2
Replace array values with another value Lodash
//REPLACE BY PASSING NEW VALUE ONLY
var arr = [1, 2, 3, 4, 5, 6];

_.fill(arr, '*');
console.log(arr);
// => ["*","*","*","*","*","*"]

_.fill(arr, 2);
console.log(arr);
// => [20,"#","#",70,80,90]

//REPLACE BY PASING - Value, start, end
const arr2 = [20, 50, 60, 70, 80, 90];
const start = 1;
const end = 3;
_.fill(arr2, '#', 1, 3);
console.log(arr2);
// => [20,"#","#",70,80,90]
Remove items begin from start until given condition is false Lodash
var users = [
    { 'user': 'Ankit', 'active': false },
    { 'user': 'John', 'active': true },
    { 'user': 'Deo', 'active': false }
];

const result = _.dropWhile(users, function (o) {
    return !o.active;
});
Remove items starting from last untill given condition is false Lodash
var users = [
    { 'user': 'Ankit', 'active': true },
    { 'user': 'John', 'active': false },
    { 'user': 'Deo', 'active': false }
];

const result = _.dropRightWhile(users, function (o) { 
    return !o.active;
});

// { 'user': 'Ankit', 'active': true }
Remove last n elements from an array using Lodash
const arr = [1, 2, 3, 4, 5, 6, 7];

//remove last element (n=1) by default
const arr1 = _.dropRight(arr);

//remove last 3 elements
const arr2 = _.dropRight(arr, 3);

//remove last 5 elements
const arr3 = _.dropRight(arr, 5);
Remove first n elements from an array using Lodash
const arr = [1, 2, 3, 4, 5, 6, 7];

//remove first element (n=1) by default
const arr1 = _.drop(arr);

//remove first 3 elements
const arr2 = _.drop(arr, 3);

//remove first 5 elements
const arr3 = _.drop(arr, 5);
Get all values from an array which does not exist in other array Lodash
const arr1 = [2, 1, 5, 6];
const arr2 = [2, 3, 10, 1];

//GET VALUES FROM arr1 that does not exist in arr2
const diff_arr = _.difference(arr1, arr2);
Merge multiple arrays and strings into single array using Lodash
const str = 50;
const arr1 = [20];
const arr2 = [30, 35];
const arr3 = [[10]]

const final_arr = _.concat(str, arr1, arr2, arr3);
Remove all false, null, undefined and empty values from array using Lodash
const arr = [5, 'one', 0, 1, false, 2, NaN, '', 3, undefined];
const new_arr = _.compact(arr)
Break an array into fixed length array groups using lodash in Javascript
const arr = ['one', 'two', 'three', 'four', 'five'];
const arr_chunks = _.chunk(arr, 2);