0

I have the following code:

var names = ["John Chuck", "Micheal Novak", "john Owen", "Rick John"];
names = _.sortBy( names, function( name ){
        return name;
     }

It gives me a sorted list of names. Now along with this if I want to do a filering, is it possible?

Its like, filter on 'John', so that final list has only 3 names with 'John' in it.

5 Answers 5

3

Try the following with Array.prototype.filter() and Array.prototype.includes():

var names = ["John Chuck", "Micheal Novak", "john Owen", "Rick John"];
names = _.sortBy( names, function( name ){
        return name;
     }).filter(n => n.toLowerCase().includes('john'));
     
console.log(names)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.core.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

1

You can use .includes in javascript

HTML

var words = ["John Chuck", "Micheal Novak", "John Owen", "Rick John"];

const result = words.filter(word => word.includes("John"));

console.log(result); //result is: Array ["John Chuck", "John Owen", "Rick John"]

Note: .includes is Case sensitive

Comments

0

No, and in your particular case, you wouldn't give the 2nd argument, because you're sorting strings (unless you want to sort by a portion of the whole string...).

You would need to filter, then sort.

Comments

0

Since you are using Lodash.js you can also look at the _.reject function

names = _.reject(names, function(name) {
              return name.match(/[.]*john[.]*/i) == undefined;
        });

This will return only the 3 names. Have a look at - JSFIDDLE DEMO

Comments

0

A simple ES6 alternative (without any libs like Lodash):

var names = ["John Chuck", "Micheal Novak", "john Owen", "Rick John"];

var result = names.sort((a, b) => a.localeCompare(b)).filter(name => /john/gi.test(name));

console.log(result);

Comments

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.