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']);
Related
I am having one array with some values like below,
let a = ["Mango","1243greatApple","goodOrange","Watermelon","ThisGoodalsoberemoved","GreatOrange","Pappaya","BestApple"];
Now, I want to eliminate the values which contains string like Great and Good in the values.
Expecting output like below,
["Mango","Watermelon","Pappaya","BestApple"]
Tried using lodash, but it works only when it matches exact string. But i need it like regex match. Please help me out with this.
In vanilla JS, you can try with Array.prototype.filter()
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
And String.prototype.includes()
The includes() method determines whether one string may be found within another string, returning true or false as appropriate.
let a = ["Mango","1243GreatApple","GoodOrange","Watermelon","ThisGoodalsoberemoved","GreatOrange","Pappaya","BestApple"];
var r = a.filter(f => !(f.includes('Great') || f.includes('Good')));
console.log(r);
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)
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')
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.
I am trying to determine whether a object contains a specific value so that I can be sure not append the value I am looking for more than once and prevent recursion.
I have tried lots of methods but can't get any of them to work:
data = [
{val:'xxx',txt:'yyy'},
{val:'yyy',txt:'aaa'},
{val:'bbb',txt:'ccc'}
];
console.log(jQuery.grep(data, function(obj){
return obj.txt === "ccc";
}));
$.map(data, function(el) {
if(el.txt === 'ccc')
console.log('found')
});
Can this be done with map() grep() or inArray() or do I really have to loop through the entire array looking for the value ??
data is an array containing multiple objects, so you'll need to specify the index of the array you wish to look in:
data[0].val === 'xxx';
data[1].val === 'yyy';
data[2].txt === 'ccc';
As an update to your function, what's wrong with $.each? You're looping anyway with map or grep, so you may as well just be honest about it :P You can loop with for as well, but I'm exampling with $.each as it's almost identical to your current code.
$.each(data, function(el) {
if(el.txt === 'ccc')
console.log('found')
});
You will have to iterate the whole array as it's an array of objects, and comparing objects is done by the references not by the values.
for (var i = 0; i < data.length; i++){
if (data[i].val == 'something')
doSomething();
}
var stExist=$.inArray(reqelement, dataArray)
If you wish to avoid all this calculations yourself, there is a utility plugin underscore.js, which has lots of helper.
One of the helpers you are looking for http://underscorejs.org/#contains.