Lodash map and return unique - javascript

I have a lodash variable;
var usernames = _.map(data, 'usernames');
which produces the following;
[
"joebloggs",
"joebloggs",
"simongarfunkel",
"chrispine",
"billgates",
"billgates"
]
How could I adjust the lodash statement so that it only returns an array of unique values? e.g.
var username = _.map(data, 'usernames').uniq();

Many ways, but uniq() isn't a method on array, it's a lodash method.
_.uniq(_.map(data, 'usernames'))
Or:
_.chain(data).map('usernames').uniq().value()
(The second is untested and possibly wrong, but it's close.)
As mentioned in the comment, depending on what your data actually is, you could do this all in one shot without first pulling out whatever usernames is.

You can also use uniqBy function which also accepts iteratee invoked for each element in the array. It accepts two arguments as below, where id is the iteratee parameter.
_.uniqBy(array, 'id')

Related

Filter an object array based on the property

The data I have stored is in a 2d Array.
One element of looks like below. (not an assignment operator)
someObjArray[5] === [{lastname:"foo", firstname:"bar", grade:10, userId:"foobar1234"},...]
For the particular above variable I want to filter on userId
I am attempting to do so like this.
var test = stuArray[5].filter(function(item) {
return item['userId'];
});
Resulting in:
test === [{lastname:"foo", firstname:"bar", grade:10, userId:"foobar1234"},...]
Where the desired results are
test === ["foobar1234",...]
I have also tried using a dot operator with the same results.
I don't think filter is what you're looking for here.
The function (non-anonymous in your case but you can also use anonymous functions) that you are passing into your filter method needs to return a true or a false. This is how the method "filters" your array - it gives you back an array whose elements pass the filter, or return true when passed as arguments into filter's function.
Note that this does not change the original array.
What you should use instead is the very similar map() function.
Note that map(), just like filter(), does not change the original array.
You can do it like this:
var someObjArray = [{lastname:"foo", firstname:"bar", grade:10, userId:"foobar1234"}];
console.log(someObjArray.map(s => s.userId));
Online demo (jsFiddle)

Lodash findIndex not working

Why is lodash returning -1 here? It's clearly in there?
Ignores = ['load', 'test', 'ok'];
alert(_.findIndex(Ignores, 'ok') );
That's because findIndex() takes as parameters an array and a predicate, a function that returns a boolean value based on some condition.
Assuming you are searching for needle in haystack, you can achieve what you want with normal JavaScript:
alert(haystack.indexOf(needle));
You can use _.indexOf (from #Juhana):
alert(_.indexOf(haystack, needle))
You can do it with _.findIndex too:
alert(_.findIndex(haystack, function(x) { return x === needle; }));
or:
alert(_.findIndex(haystack, _(needle).isEqual));
The loadash _.findIndex is quite work in different order of the JSON structure.If you would like to get the index of the array object based upon the nested structure.The lodash has provided the same special way to do it.
Let assume if your JSON structure is like below mentioned pattern.
lstMainArray:
[{searhName:'Abc1',searchName:'Abc2'}]
and you would like to search from nested JSNO such as :
searchObject :
{
searchField:{
searchName:'Abc1'
}
}
you can make the below syntax to use it.
_.findIndex(lstMainArray,['searchField.searchName','Abc1']);

Use underscore.js "pluck" on a knockout observable array

I have an observable array of objects and I want to pluck out the values using underscore.js
For example:
ko.observableArray([{
id: ko.observable(1),
name: ko.observable("name1")
},
{
id: ko.observable(2),
name: ko.observable("name2")
},
...])
And I just want to pluck the values inside of the object rather than the whole observable.
Can I do this with just one command?
I tried:
_.pluck(myArray(), "id()") and _.pluck(myArray(), "id"())
But these return an array of undefineds and "id is not a function" respectively.
Thanks!
Short answer
Use _.invoke instead of _.pluck
See this sample fiddle.
Long answer
_.pluck(list, propertyName) works as documented:
A convenient version of what is perhaps the most common use-case for map: extracting a list of property values.
Or, as better exlained on lodash docs: _.pluck(collection, path)
Gets the property value of path from all elements in collection.
So, if you do this:
_.pluck(myArray(), "id")
what you get is an array with all the id's. And all of these id's are observables, as in the objects of the original array
But you can use _.invoke(list, methodName, *arguments), which, as documented:
Calls the method named by methodName on each value in the list. Any extra arguments passed to invoke will be forwarded on to the method invocation.
or, on lodash version _.invoke(collection, path, [args])
Invokes the method at path on each element in collection, returning an array of the results of each invoked method. Any additional arguments are provided to each invoked method. If methodName is a function it is invoked for, and this bound to, each element in collection.
In this way, you execute each observable, and get its value as expected:
_.invoke(myArray(), "id")
Mind the viewmodels full of observables!
The first comment to this question has made me include this notice:
The best solution is using ko.toJS to convert all the observables in a view model into a regular JavaScript object, with regular properties. Once you do it, underscore, or any other library, will work as expected.
The _.invoke solution only works for a single level of observables, as this case. If there were several level of nested observables, it will completely fail, because it invokes a function at the end of the path, not at each step of the path, for example, _.invoke wouldn't work for this case:
var advices = [{
person: ko.observable({
name = ko.observable('John')
}),
advice: ko.observable('Beware of the observables!')
}];
In this case, you could only use _.invoke on the first level, like this:
var sentences = _.invoke(advices,'advice');
But this wouldn't work:
var names = _.invoke(advices,'person.name');
In this call, only name would be invoked, but person not, so this would fail, because person is an observable, thus it doesn't have a name property.
NOTE: lodash is another library similar, and mostly compatible with underscore, but better in some aspects
I was able to solve this by using the "map" function:
_.map(myArray(), function(item) {return item.id()});
But I was hoping to use pluck since it's the exact use-case for this type of scenario.
Because name is a function, how about pluck your original array into an array of functions, then using ko.toJS to convert it into string array?
var myArray = ko.observableArray([{
id: ko.observable(1),
name: ko.observable("name1")
},
{
id: ko.observable(2),
name: ko.observable("name2")
}]);
var names = _.pluck(myArray(), 'name');
console.log(ko.toJS(names)); // Output: ["name1", "name2"]
Unwrap it first
_.pluck(ko.toJS(myArray), 'id')
_(ko.toJS(myArray)).pluck('id)

Need help understanding lodash's _.includes method

I would like to use lodash's _.includes method in my code, but any time I have an array of objects I can't get it to work, and instead end up relying on the _.find method.
From my tests I can only get _.includes to work with simply arrays. But maybe that's the way it's supposed to work?
I am very new to Lodash and programming in general, so I thought I would ask in case I am missing something about how I can use this method.
I created a jsbin with the following code: http://jsbin.com/regojupiro/2/
var myArray = [];
function createArray(attName, attId, otherId) {
var theObject = {};
theObject.attributeName = attName;
theObject.attributeId = attId;
theObject.otherId = [otherId];
return theObject;
}
myArray.push(createArray('first', 1001, 301));
myArray.push(createArray('second', 1002, 302));
myArray.push(createArray('third', 1003, 303));
myArray.push(createArray('fourth', 1004, 304));
var isPresent1 = _.includes(myArray, {'attribtueId' : 1001});
var isPresent2 = _.includes(myArray, 1001);
var found = _.find(myArray, {'attributeId' : 1001});
console.log(isPresent1);
console.log(isPresent2);
console.log(found);
console.log(myArray);
Both "isPresent" variables return false, but the _.find method returns the correct object.
I would love some help in better understanding how I could use the _.includes method when I just need to do a simple true/false check to see if a value is present in my array of objects.
Or, if this is the wrong tool for the job, is the _.find method the right tool for this job, or some other lodash method that I'm not familiar with yet?
Thank you for your help!
I think some() does exactly what you're looking for.
The _.includes() method compares with the SameValueZero comparator, which is a special comparison mostly like ===. Even if you have an object in your array that looks like {'attribtueId' : 1001} that _.includes() call will never find it because two distinct objects will never compare as === to each other.
When you pass an object to _.find(), by contrast, the library assumes that you want it to carry out an _.matches() comparison, which will compare properties of the "target" object. Thus, in your case, _.find() is probably the right choice. The _.includes method really fills a distinct niche.

How to push the array of data to another array through javascript without loop

I have an Json array like data {"alphaNumeric":[]}.
Here I just want to push the another array [mentioned below] of objects to this Data with out loop concept.
data{"numeric":[{"id":"1","alpha":"a"},{"id":"2","alpha":"b"}]}.
I used the below code :
data.alphaNumeric.push(data.numeric);
but the output is :
data{"alphaNumeric":[[{"id":"1","alpha":"a"},{"id":"2","alpha":"b"}]]}.
Expected :
data{"alphaNumeric":[{"id":"1","alpha":"a"},{"id":"2","alpha":"b"}]}.
Help me to resolve.
One solution may be using the concat method. Which isn't really good as it creates a whole new array.
b.alphaNumeric = b.alphaNumeric.concat(a.numeric);
But there is a much better solution using push. It accepts more than just one element, but unfortunately not as an array. This can be however achieved using its apply method:
b.alphaNumeric.push.apply(b.alphaNumeric, a.numeric);
Also you can write your own method (I call it add) which will do this action for you:
Array.prototype.add = function (array) {
this.push.apply(this, array);
return this;
};
b.alphaNumeric.add(a.numeric);
Use concat()
data.alphaNumeric.concat(data.numeric);
.push() and .pop() are for adding and removing single elements in an array. The return value from .concat() is what you're looking for:
var newArr = oldArr.concat(extraArr);

Categories