Related
I have an sorted array e.g
var arr = [ "aasd","march","mazz" ,"xav" ];
And i want to find the first occurance of letter that starts with "m" here it would be 1 . Is thee any way how to do it without looping trought whole array?
You could use a binary search to find any word starting with that letter, then loop backwards until you get the first one.
Is there any way how to do it without looping trought whole array?
Yes, loop until you've found the match.
If you want to avoid a for or while construct, you can use Array's find() method.
For example, arr.find(word => word.startsWith("m")) should return the result you expect (or undefined if there's no such word).
You could use the find() function to search for the first match that meets your constraint.
The startsWith() function could easily handle this :
// Your array
var arr = [ "aasd","march","mazz" ,"xav" ];
// This will find the first match that starts with "m"
arr.find(function(word){ return word.startsWith('m');}); // yields "march"
Or if you needed a bit more extensive pattern matching, you could use a regular expression via the test() function, which can be seen in the following example and handles the same scenario (matching a string that begins with "m") :
// Your array
var arr = [ "aasd","march","mazz" ,"xav" ];
// First match that starts with "m"
var match = arr.find(function(word){ return /^m/i.test(word);}); // yields "march"
Example
var arr = ["aasd", "march", "mazz", "xav"];
var match = arr.find(function(word) { return /^m/i.test(word); });
alert(match);
You dont need to loop through the whole array - only until such time as you find what you're interested in
function findFirstIndex(arr, char){
for(var i=0;i<arr.length;i++){
if(arr[i].substring(0,1) === char)
return i;
}
return -1; // not found
}
You could use Array#some()
The some() method tests whether some element in the array passes the test implemented by the provided function.
function find(letter, array) {
var index;
array.some(function (a, i) {
if (a[0] === letter) {
index = i;
return true;
}
});
return index;
}
var arr = ["aasd", "march", "mazz", "xav"];
document.write(find('m', arr));
I have a String Array containing elements starting with a letter then a colon and then some random text. Example:
a = [
"a:aushdad",
"b:ofigjhld",
"g:dkfgjdfg",
"b:kjfdgkdfj"
]
I want to keep only the first element starting with b: and the same for any other duplicates there might be.
The end result should be:
a = [
"a:aushdad",
"b:ofigjhld",
"g:dkfgjdfg",
]
How could this be achieved? Let me know if you need any more information.
You could use Array.reduce:
var a = [
"a:aushdad",
"b:ofigjhld",
"g:dkfgjdfg",
"b:kjfdgkdfj"
]
var letters = [];
var result = a.reduce(function(prev,current){
if(letters.indexOf(current[0]) === -1) {
letters.push(current[0]);
prev.push(current);
}
return prev;
}, []);
console.log(result); // ["a:aushdad", "b:ofigjhld", "g:dkfgjdfg"]
You can use filter from array.
//store already used 'key'
var map = {};
//regexp used to get the interesting part
var regexp = /^.*?:/;
//function used for the filter, true add the value to the result array.
function myFilter(value){
//get the key
var key = regexp.exec(value)[0];
//key not null and not used ?
if(key && !map[key]){
map[key] = true;
return true;
}
else{
return false;
}
}
var result = myArray.filter(myFilter);
I have:
var array = new Array();
array.push("A");
array.push("B");
array.push("C");
I want to be able to do something like:
array.remove("B");
but there is no remove function. How do I accomplish this?
I'm actually updating this thread with a more recent 1-line solution:
let arr = ['A', 'B', 'C'];
arr = arr.filter(e => e !== 'B'); // will return ['A', 'C']
The idea is basically to filter the array by selecting all elements different to the element you want to remove.
Note: will remove all occurrences.
EDIT:
If you want to remove only the first occurence:
t = ['A', 'B', 'C', 'B'];
t.splice(t.indexOf('B'), 1); // will return ['B'] and t is now equal to ['A', 'C', 'B']
Loop through the list in reverse order, and use the .splice method.
var array = ['A', 'B', 'C']; // Test
var search_term = 'B';
for (var i=array.length-1; i>=0; i--) {
if (array[i] === search_term) {
array.splice(i, 1);
// break; //<-- Uncomment if only the first term has to be removed
}
}
The reverse order is important when all occurrences of the search term has to be removed. Otherwise, the counter will increase, and you will skip elements.
When only the first occurrence has to be removed, the following will also work:
var index = array.indexOf(search_term); // <-- Not supported in <IE9
if (index !== -1) {
array.splice(index, 1);
}
List of One Liners
Let's solve this problem for this array:
var array = ['A', 'B', 'C'];
1. Remove only the first:
Use If you are sure that the item exist
array.splice(array.indexOf('B'), 1);
2. Remove only the last:
Use If you are sure that the item exist
array.splice(array.lastIndexOf('B'), 1);
3. Remove all occurrences:
array = array.filter(v => v !== 'B');
DEMO
You need to find the location of what you're looking for with .indexOf() then remove it with .splice()
function remove(arr, what) {
var found = arr.indexOf(what);
while (found !== -1) {
arr.splice(found, 1);
found = arr.indexOf(what);
}
}
var array = new Array();
array.push("A");
array.push("B");
array.push("C");
remove(array, 'B');
alert(array);
This will take care of all occurrences.
Simply
array.splice(array.indexOf(item), 1);
Simple solution (ES6)
If you don't have duplicate element
Array.prototype.remove = function(elem) {
var indexElement = this.findIndex(el => el === elem);
if (indexElement != -1)
this.splice(indexElement, 1);
return this;
};
Online demo (fiddle)
const changedArray = array.filter( function(value) {
return value !== 'B'
});
or you can use :
const changedArray = array.filter( (value) => value === 'B');
The changedArray will contain the without value 'B'
In case of wanting to remove array of strings from array of strings:
const names = ['1','2','3','4']
const excludeNames = ['2','3']
const filteredNames = names.filter((name) => !excludeNames.includes(name));
// ['1','4']
You have to write you own remove. You can loop over the array, grab the index of the item you want to remove, and use splice to remove it.
Alternatively, you can create a new array, loop over the current array, and if the current object doesn't match what you want to remove, put it in a new array.
use:
array.splice(2, 1);
This removes one item from the array, starting at index 2 (3rd item)
use array.splice
/*array.splice(index , howMany[, element1[, ...[, elementN]]])
array.splice(index) // SpiderMonkey/Firefox extension*/
array.splice(1,1)
Source:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
This only valid on str list, look up this
myStrList.filter(item=> !["deletedValue","deletedValue2"].includes(item))
Here is the simplest answer.
First find index using indexofand then
if index exist use splice
const array = ['apple', 'banana', 'orange', 'pear'];
const index = array.indexOf('orange'); // Find the index of the element to remove
if (index !== -1) { // Make sure the element exists in the array
array.splice(index, 1); // Remove the element at the found index
}
console.log(array); // ["apple", "banana", "pear"]
Pretty straight forward. In javascript, I need to check if a string contains any substrings held in an array.
There's nothing built-in that will do that for you, you'll have to write a function for it, although it can be just a callback to the some array method.
Two approaches for you:
Array some method
Regular expression
Array some
The array some method (added in ES5) makes this quite straightforward:
if (substrings.some(function(v) { return str.indexOf(v) >= 0; })) {
// There's at least one
}
Even better with an arrow function and the newish includes method (both ES2015+):
if (substrings.some(v => str.includes(v))) {
// There's at least one
}
Live Example:
const substrings = ["one", "two", "three"];
let str;
// Setup
console.log(`Substrings: ${substrings}`);
// Try it where we expect a match
str = "this has one";
if (substrings.some(v => str.includes(v))) {
console.log(`Match using "${str}"`);
} else {
console.log(`No match using "${str}"`);
}
// Try it where we DON'T expect a match
str = "this doesn't have any";
if (substrings.some(v => str.includes(v))) {
console.log(`Match using "${str}"`);
} else {
console.log(`No match using "${str}"`);
}
Regular expression
If you know the strings don't contain any of the characters that are special in regular expressions, then you can cheat a bit, like this:
if (new RegExp(substrings.join("|")).test(string)) {
// At least one match
}
...which creates a regular expression that's a series of alternations for the substrings you're looking for (e.g., one|two) and tests to see if there are matches for any of them, but if any of the substrings contains any characters that are special in regexes (*, [, etc.), you'd have to escape them first and you're better off just doing the boring loop instead. For info about escaping them, see this question's answers.
Live Example:
const substrings = ["one", "two", "three"];
let str;
// Setup
console.log(`Substrings: ${substrings}`);
// Try it where we expect a match
str = "this has one";
if (new RegExp(substrings.join("|")).test(str)) {
console.log(`Match using "${str}"`);
} else {
console.log(`No match using "${str}"`);
}
// Try it where we DON'T expect a match
str = "this doesn't have any";
if (new RegExp(substrings.join("|")).test(str)) {
console.log(`Match using "${str}"`);
} else {
console.log(`No match using "${str}"`);
}
One line solution
substringsArray.some(substring=>yourBigString.includes(substring))
Returns true\false if substring exists\does'nt exist
Needs ES6 support
var yourstring = 'tasty food'; // the string to check against
var substrings = ['foo','bar'],
length = substrings.length;
while(length--) {
if (yourstring.indexOf(substrings[length])!=-1) {
// one of the substrings is in yourstring
}
}
function containsAny(str, substrings) {
for (var i = 0; i != substrings.length; i++) {
var substring = substrings[i];
if (str.indexOf(substring) != - 1) {
return substring;
}
}
return null;
}
var result = containsAny("defg", ["ab", "cd", "ef"]);
console.log("String was found in substring " + result);
For people Googling,
The solid answer should be.
const substrings = ['connect', 'ready'];
const str = 'disconnect';
if (substrings.some(v => str === v)) {
// Will only return when the `str` is included in the `substrings`
}
Here's what is (IMO) by far the best solution. It's a modern (ES6) solution that:
is efficient (one line!)
avoids for loops
unlike the some() function that's used in the other answers, this one doesn't just return a boolean (true/false)
instead, it either returns the substring (if it was found in the array), or returns undefined
goes a step further and allows you to choose whether or not you need partial substring matches (examples below)
Enjoy!
const arrayOfStrings = ['abc', 'def', 'xyz'];
const str = 'abc';
const found = arrayOfStrings.find(v => (str === v));
Here, found would be set to 'abc' in this case. This will work for exact string matches.
If instead you use:
const found = arrayOfStrings.find(v => str.includes(v));
Once again, found would be set to 'abc' in this case. This doesn't allow for partial matches, so if str was set to 'ab', found would be undefined.
And, if you want partial matches to work, simply flip it so you're doing:
const found = arrayOfStrings.find(v => v.includes(str));
instead. So if str was set to 'ab', found would be set to 'abc'.
Easy peasy!
var str = "texttexttext";
var arr = ["asd", "ghj", "xtte"];
for (var i = 0, len = arr.length; i < len; ++i) {
if (str.indexOf(arr[i]) != -1) {
// str contains arr[i]
}
}
edit:
If the order of the tests doesn't matter, you could use this (with only one loop variable):
var str = "texttexttext";
var arr = ["asd", "ghj", "xtte"];
for (var i = arr.length - 1; i >= 0; --i) {
if (str.indexOf(arr[i]) != -1) {
// str contains arr[i]
}
}
substringsArray.every(substring=>yourBigString.indexOf(substring) === -1)
For full support ;)
For full support (additionally to #ricca 's verions).
wordsArray = ['hello', 'to', 'nice', 'day']
yourString = 'Hello. Today is a nice day'.toLowerCase()
result = wordsArray.every(w => yourString.includes(w))
console.log('result:', result)
If the array is not large, you could just loop and check the string against each substring individually using indexOf(). Alternatively you could construct a regular expression with substrings as alternatives, which may or may not be more efficient.
Javascript function to search an array of tags or keywords using a search string or an array of search strings. (Uses ES5 some array method and ES6 arrow functions)
// returns true for 1 or more matches, where 'a' is an array and 'b' is a search string or an array of multiple search strings
function contains(a, b) {
// array matches
if (Array.isArray(b)) {
return b.some(x => a.indexOf(x) > -1);
}
// string match
return a.indexOf(b) > -1;
}
Example usage:
var a = ["a","b","c","d","e"];
var b = ["a","b"];
if ( contains(a, b) ) {
// 1 or more matches found
}
This is super late, but I just ran into this problem. In my own project I used the following to check if a string was in an array:
["a","b"].includes('a') // true
["a","b"].includes('b') // true
["a","b"].includes('c') // false
This way you can take a predefined array and check if it contains a string:
var parameters = ['a','b']
parameters.includes('a') // true
Best answer is here:
This is case insensitive as well
var specsFilter = [.....];
var yourString = "......";
//if found a match
if (specsFilter.some((element) => { return new RegExp(element, "ig").test(yourString) })) {
// do something
}
const str = 'Does this string have one or more strings from the array below?';
const arr = ['one', 'two', 'three'];
const contains = arr.some(element => {
if (str.includes(element)) {
return true;
}
return false;
});
console.log(contains); // true
Not that I'm suggesting that you go and extend/modify String's prototype, but this is what I've done:
String.prototype.includes()
String.prototype.includes = function (includes) {
console.warn("String.prototype.includes() has been modified.");
return function (searchString, position) {
if (searchString instanceof Array) {
for (var i = 0; i < searchString.length; i++) {
if (includes.call(this, searchString[i], position)) {
return true;
}
}
return false;
} else {
return includes.call(this, searchString, position);
}
}
}(String.prototype.includes);
console.log('"Hello, World!".includes("foo");', "Hello, World!".includes("foo") ); // false
console.log('"Hello, World!".includes(",");', "Hello, World!".includes(",") ); // true
console.log('"Hello, World!".includes(["foo", ","])', "Hello, World!".includes(["foo", ","]) ); // true
console.log('"Hello, World!".includes(["foo", ","], 6)', "Hello, World!".includes(["foo", ","], 6) ); // false
building on T.J Crowder's answer
using escaped RegExp to test for "at least once" occurrence, of at least one of the substrings.
function buildSearch(substrings) {
return new RegExp(
substrings
.map(function (s) {return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');})
.join('{1,}|') + '{1,}'
);
}
var pattern = buildSearch(['hello','world']);
console.log(pattern.test('hello there'));
console.log(pattern.test('what a wonderful world'));
console.log(pattern.test('my name is ...'));
Drawing from T.J. Crowder's solution, I created a prototype to deal with this problem:
Array.prototype.check = function (s) {
return this.some((v) => {
return s.indexOf(v) >= 0;
});
};
Using underscore.js or lodash.js, you can do the following on an array of strings:
var contacts = ['Billy Bob', 'John', 'Bill', 'Sarah'];
var filters = ['Bill', 'Sarah'];
contacts = _.filter(contacts, function(contact) {
return _.every(filters, function(filter) { return (contact.indexOf(filter) === -1); });
});
// ['John']
And on a single string:
var contact = 'Billy';
var filters = ['Bill', 'Sarah'];
_.every(filters, function(filter) { return (contact.indexOf(filter) >= 0); });
// true
If you're working with a long list of substrings consisting of full "words" separated by spaces or any other common character, you can be a little clever in your search.
First divide your string into groups of X, then X+1, then X+2, ..., up to Y. X and Y should be the number of words in your substring with the fewest and most words respectively. For example if X is 1 and Y is 4, "Alpha Beta Gamma Delta" becomes:
"Alpha" "Beta" "Gamma" "Delta"
"Alpha Beta" "Beta Gamma" "Gamma Delta"
"Alpha Beta Gamma" "Beta Gamma Delta"
"Alpha Beta Gamma Delta"
If X would be 2 and Y be 3, then you'd omit the first and last row.
Now you can search on this list quickly if you insert it into a Set (or a Map), much faster than by string comparison.
The downside is that you can't search for substrings like "ta Gamm". Of course you could allow for that by splitting by character instead of by word, but then you'd often need to build a massive Set and the time/memory spent doing so outweighs the benefits.
convert_to_array = function (sentence) {
return sentence.trim().split(" ");
};
let ages = convert_to_array ("I'm a programmer in javascript writing script");
function confirmEnding(string) {
let target = "ipt";
return (string.substr(-target.length) === target) ? true : false;
}
function mySearchResult() {
return ages.filter(confirmEnding);
}
mySearchResult();
you could check like this and return an array of the matched words using filter
I had a problem like this. I had a URL, I wanted to check if the link ends in an image format or other file format, having an array of images format. Here is what I did:
const imagesFormat = ['.jpg','.png','.svg']
const link = "https://res.cloudinary.com/***/content/file_padnar.pdf"
const isIncludes = imagesFormat.some(format => link.includes(format))
// false
You can check like this:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var list = ["bad", "words", "include"]
var sentence = $("#comments_text").val()
$.each(list, function( index, value ) {
if (sentence.indexOf(value) > -1) {
console.log(value)
}
});
});
</script>
</head>
<body>
<input id="comments_text" value="This is a bad, with include test">
</body>
</html>
let obj = [{name : 'amit'},{name : 'arti'},{name : 'sumit'}];
let input = 'it';
Use filter :
obj.filter((n)=> n.name.trim().toLowerCase().includes(input.trim().toLowerCase()))
var str = "A for apple"
var subString = ["apple"]
console.log(str.includes(subString))
Here is the case:
I want to find the elements which match the regex...
targetText = "SomeT1extSomeT2extSomeT3extSomeT4extSomeT5extSomeT6ext"
and I use the regex in javascript like this
reg = new RegExp(/e(.*?)e/g);
var result = reg.exec(targetText);
and I only get the first one, but not the follow....
I can get the T1 only, but not T2, T3 ... ...
var reg = /e(.*?)e/g;
var result;
while((result = reg.exec(targetText)) !== null) {
doSomethingWith(result);
}
Three approaches depending on what you want to do with it:
Loop through each match: .match
targetText.match(/e(.*?)e/g).forEach((element) => {
// Do something with each element
});
Loop through and replace each match on the fly: .replace
const newTargetText = targetText.replace(/e(.*?)e/g, (match, $1) => {
// Return the replacement leveraging the parameters.
});
Loop through and do something on the fly: .exec
const regex = /e(.*?)e/g; // Must be declared outside the while expression,
// and must include the global "g" flag.
let result;
while(result = regex.exec(targetText)) {
// Do something with result[0].
}
Try using match() on the string instead of exec(), though you could loop with exec as well. Match should give you the all the matches at one go. I think you can omit the global specifier as well.
reg = new RegExp(/e(.*?)e/);
var matches = targetText.match(reg);
I kept getting infinite loops while following the advice above, for example:
var reg = /e(.*?)e/g;
var result;
while((result = reg.exec(targetText)) !== null) {
doSomethingWith(result);
}
The object that was assigned to result each time was:
["", "", index: 50, input: "target text", groups: undefined]
So in my case I edited the above code to:
const reg = /e(.*?)e/g;
let result = reg.exec(targetText);
while(result[0] !== "") {
doSomethingWith(result);
result = reg.exec(targetText);
}
targetText = "SomeT1extSomeT2extSomeT3extSomeT4extSomeT5extSomeT6ext"
reg = new RegExp(/e(.*?)e/g);
var result;
while (result = reg.exec(targetText))
{
...
}
You could also use the String.replace method to loop through all elements.
result = [];
// Just get all numbers
"SomeT1extSomeT2extSomeT3ext".replace(/(\d+?)/g, function(wholeMatch, num) {
// act here or after the loop...
console.log(result.push(num));
return wholeMatch;
});
console.log(result); // ['1', '2', '3']
Greetings
I did this in a console session (Chrome).
> let reg = /[aeiou]/g;
undefined
> let text = "autoeciously";
undefined
> matches = text.matches(reg);
(7) ["a", "u", "o", "e", "i", "o", "u"]
> matches.forEach(x =>console.log(x));
a
u
o
e
i
o
u
Although #tvanfosson suggested in his answer, I'm adding the modified version for someone who only needs to get all matchings.
var targetText = "SomeT1extSomeT2extSomeT3extSomeT4extSomeT5extSomeT6ext";
var reg = /e(.*?)e/g;
var ss = targetText.match(reg); // ss = "eT1e,eT2e,eT3e,eT4e,eT5e,eT6e"
I was actually dealing with this issue. I prefer Lambda functions for about everything.
reg = /e(.*?)e/gm;
targetText.match(reg).forEach(element => console.log(element));