Javascript list contains a string [duplicate] - javascript

This question already has answers here:
Determine whether an array contains a value [duplicate]
(18 answers)
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 6 years ago.
Does anyone know of a way to check if a list contains a string without using indexOf? In my array some strings can contains parts of others, so indexOf will produce false positives.
As an example, how would I determine if "component" is in the array below?
["component.part", "random-component", "prefix-component-name", "component"]
Update:
It seems like my use of false positive was misleading. I meant that it would say that component was in there 4 times, when I want to match the string by itself.
ie. It should return false when checking for the presence of "component" in the below array.
["component.part", "random-component", "prefix-component-name"]

Use the Array.find API.
Example:
"use strict";
let items = ["component.part", "random-component", "prefix-component-name", "component"];
let found = items.find(item => { return item === "component.part" } );
if (found) {
console.log("Item exists.");
}
For more usage example.
See:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find

One way is to use .find() to get the string you want from the Array.

Try using $.inArray() method.
var list=["component.part", "random-component", "prefix-component-name", "component"];
if($.inArray(" component",list) != -1){
console.log("Item found");
}

Does anyone know of a way to check if a list contains a string without using indexOf? In my array some strings can contains parts of others, so indexOf will produce false positives.
false positives? Array.prototype.indexOf and Array.prototype.includes both use strict equality which makes that impossible here.

IndexOf won't give you false positive. It will give you 3. If you want to find all elements that has "otherstuff componenet" you can loop through your array and check with String.includes()
Here is a beginner friendly solution.
var arr = ["component.part", "random-component",
"prefix-component-name", "component", "asdf"];
console.log(arr.indexOf('component')); // give u 3
for (var i = 0; i < arr.length; i++){
if (arr[i].includes('component')){
console.log(arr[i]);
}
}

Related

Array from GroupsApp and then indexOf fails [duplicate]

This question already has answers here:
indexOf method in an object array?
(29 answers)
Why doesn't indexOf find an array within the searched array? (Need explanation not solution) [duplicate]
(3 answers)
Closed 1 year ago.
I am trying to get a list of people in a Google Group with Google Apps Script. I made a code (below) but the result is unexpected. I think is realted with the format of the item but not sure. In my code i tested many logs to check that.
Why "indexOf" can not detect properly the email? Becuase -1.00 as answer is wrong.
Info:
getUsers() User[] Retrieves the direct members of the group that have a known corresponding Google account.
I think is weird indexOf answering -1.00 when i ask with "" and when i ask with the position of array answer properly.
I need to check in an script if someone is inside of this groups (inside loop for).
function CheckingSomeFromGroup() {
var members = GroupsApp.getGroupByEmail("members#company").getUsers();
Logger.log(members); //it shows an array in the log
Logger.log(members[0]); //it shows the first element form that array which is "Jorge#company.com"
Logger.log(members.indexOf("Jorge#company.com") //i was expecting a number different than -1.00 because jorge exists but in the log appear -1.00 which is wrong
Logger.log(members.indexOf(members[0]); //it shows 0 correctly becuase Jorge is in the first place of the array
Logger.log(members.length);//it shows number 3 which is ok since i have 3 people in the group
}
members is an array of User object, not string. So you cannot just find it by email/string. You see email in the logger because it might have a toString method to output that.
You can loop on members and call User.getEmail() to get the email and work accordingly.
function CheckingSomeFromGroup() {
var emails = ['abc#example.com'];//get 1-D array of string emails from your column accordingly
var members = GroupsApp.getGroupByEmail("members#company").getUsers();
for (var i = 0; i < members.length; i++) {
var memberEmail = members[i].getEmail();
if (emails.indexOf(memberEmail) !== -1) {
//exists
}
}
}

Finding last occurences of element in Array of Array with lastIndexOf [duplicate]

This question already has answers here:
Find last index of element inside array by certain condition
(23 answers)
Closed 2 years ago.
Is it possible somehow to use the lastIndexOf method to get the value of a variable in an array of array? For example if I had
[[1,2,3,4],[4,6,4,7,5], [5,7,4,6,3], [6,2,5,4,3]]
and I wanted to find the index of the last array where [1] was 2? In the above I would expect the answer to be 3 as the third array has [1] equal to 2.
I can see how I can make this work with nested loops or array methods but just wondered if there's some syntax I'm not aware of. Cheers
No.
Because Array.prototype.lastIndexOf() only accepts an element, and not a callback, you can't use lastIndexOf() for this case directly.
Given this, and that there's no standard findLastIndex() prototype function, you'll have to write this functionality yourself. Here's one such way, using reduce() and findIndex(), while avoiding mutating the original array:
const arr = [[1,2,3,4],[4,6,4,7,5], [5,7,4,6,3], [6,2,5,4,3]];
function findLastIndex(arr, callback) {
return (arr.length - 1) - // Need to subtract found, backwards index from length
arr.slice().reverse() // Get reversed copy of array
.findIndex(callback); // Find element satisfying callback in rev. array
}
console.log(findLastIndex(arr, (e) => e[1] == 2));
I discovered arr.slice().reverse() from this answer by user #Rajesh, which is much faster than my previous reducer.

How to filter array of objects and only return one result without the array brackets [duplicate]

This question already has answers here:
How to find first element of array matching a boolean condition in JavaScript?
(14 answers)
Closed 3 years ago.
I may not have had enough coffee on this lovely monday morning but there's something simple I'd like to do that is not coming to me.
I am filtering on an array of objects for an id:
const skuVariant = skuOptions.filter(sku => sku.itemNumber === variantItemNumber);
This returns an array that is of length 1 if there is a match.
The following line I have:
const skuVariantValueMap = skuVariant && skuVariant[0].varianceValueMap;
I would like to not have to check the for the first element of the array and instead only return the object from the call to filter and not the object inside an array.
To be extra clear skuVariant returns this: [{id: 1234}]
I would like it to return this: { id: 1234 }
This is possible using lodash utils but that's overkill. I am looking for something vanilla.
Is there an ES7, ES6 / super clean way of achieving this?
Thanks in advance.
Use Array.prototype.find instead of filter. It returns the value of the first element in the array that satisfies the provided testing function.

use lodash to find substring from array of strings

I'm learning lodash. Is it possible to use lodash to find a substring in an array of strings?
var myArray = [
'I like oranges and apples',
'I hate banana and grapes',
'I find mango ok',
'another array item about fruit'
]
is it possible to confirm if the word 'oranges' is in my array?
I've tried _.includes, _.some, _.indexOf but they all failed as they look at the full string, not a substring
You can easily construct an iteratee for some() using lodash's higher-order functions. For example:
_.some(myArray, _.unary(_.partialRight(_.includes, 'orange')));
The unary() function ensures that only one argument is passed to the callback. The partialRight() function is used to apply the 'orange' value as the second argument to includes(). The first argument is supplied with each iteration of some().
However, this approach won't work if case sensitivity matters. For example, 'Orange' will return false. Here's how you can handle case sensitivity:
_.some(myArray, _.method('match', /Orange/i));
The method() function creates a function that will call the given method of the first argument passed to it. Here, we're matching against a case-insensitive regular expression.
Or, if case-sensitivity doesn't matter and you simply prefer the method() approach, this works as well for ES2015:
_.some(myArray, _.method('includes', 'orange'));
Two quick ways to do it - neither uses lodash (sorry)
var found = myArray.filter(function(el){
return el.indexOf('oranges') > -1;
}).length;
if (found) { // oranges was found }
or as I mentioned in the comment:
var found = myArray.join(',').indexOf('oranges') > -1;
if (found) { // oranges was found }
You can do this using lodash, but it's also very doable using native javascript methods:
function stringArrayContains(array, str) {
function contains(el) {
return (el.indexOf(str) !== -1) ? true : false;
}
return array.some(contains);
}
Testing the above function:
var a = ['hello', 'there'];
var b = ['see', 'ya', 'later'];
stringArrayContains(a, 'ell') // true
stringArrayContains(a, 'what') // false
stringArrayContains(b, 'later') // true
stringArrayContains(b, 'hello') // false
Array.prototype.some applies a function you define to every element of an array. This function (named contains in our case) must return true or false. While iterating through the array elements, if any of the elements returns true, the some method returns true.
Personally, I think in general that if you can use native JS methods for simple functions, it's preferable to loading an library just to do the same thing. Lodash absolutely does have performance benefits, but they aren't necessarily realized unless you're processing large amounts of data. Just my two cents.
Cheers!
The best way is to define a function to check the inclusion of a substring.
var contains = _.curry(function (substring, source) {
return source.indexOf(substring) !== -1;
});
I use _.curry here to get a curried function, which can be partially applied then.
_.some(myArray, contains('item'));
You can also find a substring in a joined string.
contains('item', _.join(myArray))
UPD:
I have not noticed that lodash already has a function to find value in a collection.
The function _.includes is quite the same to what I defined above. However, as everything in lodash, it uses the different order for arguments. In my example, I put a source as the latest argument for a curried function which makes my function useful for point-free style programming when lodash waits for the source as a first argument of the same function.
Check the Brian Lonsdorf's talk on this matter https://www.youtube.com/watch?v=m3svKOdZijA
Also take a chance to look into ramda. This library provides a better way for practical functional programming in JavaScript.
I ran into this Question / Answer thread while trying to figure out how to match a substring against each String in an Array and REMOVE any array item that contains that substring.
While the above answers put me on track, and while this doesn't specifically answer the original question, this thread DOES appear first in the google search when you are trying to figure out how to accomplish the above removal of an array item so I figured I would post an answer here.
I ended up finding a way to use Lodash's _.remove function to remove matching array strings as follows:
// The String (SubString) we want to match against array (for dropping purposes)
var searchSubString = "whatever"
// Remove all array items that contain the text "whatever"
_.remove(my_array, function(searchSubString) {
return n.indexOf(searchSubString) !== -1;
});
Basically indexOf is matching against the position of the substring within the string, if the substring is not found it will return -1, when indexOf returns a number other than -1 (the number is the SubString position in number of characters within the Array string).
Lodash removes that Array item via array mutation and the newly modified array can be accessed by the same name.
_.some(myArray, function(str){
return _.includes(str, 'orange')
})
let str1 = 'la rivière et le lapin sont dans le près';
let str2 = 'product of cooking class';
let str3 = 'another sentence to /^[analyse]/i with weird!$" chars#';
_.some(_.map(['rabbit','champs'], w => str1.includes(w)), Boolean), // false
_.some(_.map(['cook'], w => str2.includes(w)), Boolean), // true
_.some(_.map(['analyse'], w => str3.includes(w)), Boolean), // true

Array with numbers 1-20 [duplicate]

This question already has answers here:
How to create an array containing 1...N
(77 answers)
Closed 9 years ago.
I'm brand new to javascript. I was working through a problem earlier where I needed an array that included the numbers 1 thru 20.
I did this with the following:
var numberArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
QUESTION:
I can't help but think that this is not efficient (and certainly not scalable). Is there a way to create an array that automatically populates with sequential values between 1 and 20, or 1 and 1000 for instance?
Here's a oneliner:
var myArr = Array(20).join().split(',').map(function(a){return this.i++},{i:1});
or a tiny bit shorter:
var myArr = (''+Array(20)).split(',').map(function(){return this[0]++;}, [1]);
Both methods create an empty Array with 20 empty elements (i.e. elements with value undefined). On a thus created Array the map method can't be applied 1, so the join (or string addition) and split trick transforms it to an Array that knows it. Now the map callback (see the MDN link) does nothing more than sending an increment of the initial value ({i:1} or [1]) back for each element of the Array, and after that, myArr contains 20 numeric values from 1 to 20.
Addendum: ES20xx
[...Array(21).keys()].slice(1);
Array.map => See also...
See also this Stackblitz project.
1 Why not? See this SO answer, and this one for a more profound explanation
You could use a simple loop to do what you want;
var numberArray = [];
for(var i = 1; i <= 20; i++){
numberArray.push(i);
}
console.log(numberArray);

Categories

Resources