1

I want to return a filtered array containing only a specified value

var messages: [{
     id: 1,
     name: "John",
     hashtag: ["#cool"]},

     {id: 2,
     name: "Bob",
     hashtag: ["#cool", "#sweet"]},

     {id: 3,
     name: "Bob",
     hashtag: ["#sweet"]} ];

// supposed to return the first two items in the array
var newArray = _.where(messages, {hashtag: "#cool"});
2
  • 1
    You may want to use filter with an explicit predicate function. where won't match a string against an array. Commented Sep 27, 2017 at 18:57
  • messages.filter(m => m.hashtag.find(h => h === '#cool')) should be a plain and simple vanilla js function that is sufficient for your needs. Commented Sep 27, 2017 at 19:15

3 Answers 3

0

Here is a purely functional way you can do it with underscore, though, much prefer Ramda for this kind of thing:

var messages = [{
    id: 1,
    name: "John",
    hashtag: ["#cool"]
  },

  {
    id: 2,
    name: "Bob",
    hashtag: ["#cool", "#sweet"]
  },

  {
    id: 3,
    name: "Bob",
    hashtag: ["#sweet"]
  }
]

var newArray = _.filter(messages, _.compose(_.partial(_.contains, _, '#cool'), _.property('hashtag')))

console.log(newArray)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

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

Comments

0

you can good use Filter, but your object hast some syntax errors. the values must be in string. show this example:

var messages=[ {
     id: 1,
     name: "John",
     hashtag: ["#cool"] },

     {id: 2,
     name: "Bob",
     hashtag: ["#cool"," #sweet"] },

     {id: 3,
     name: "Bob",
     hashtag: ["#sweet"]
	 }];
	var newArray=messages.filter(function(task){ return task.hashtag.includes("#cool") });

	console.log(newArray);

Comments

0

You can't filter the array stored in "hashtag" using _.where (because it searches for a string in a key-value pair) but you can do it using _.filter

var filtered = _.filter( messages, function( message ){
    return message['hashtag'].indexOf('#cool') !== -1;
} );

Little codepen to demonstrate it working: https://codepen.io/iwantwin/pen/oGWNzv

Comments

Your Answer

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