Filtering numbers out from an array - javascript

I have an array like below and need to filter out the numbers from it ex: [1,2]
var str = [
"https://xx.jpg",
"https://xx.jpg",
"1",
"https://guide.jpg",
"2",
"/static.jpg"
]
I have the below code :
var filtered = str.filter(function(item) {
return (typeof item === "number")
});
but it is not filtering as it is a string.
How to do it?

I think this is the most precise way to filter out numbers from an array.
str.filter(Number);
If the array contains a number in the form of string, then the resulting array will have the number in the form of string. In your case, the resulting array will be ["1", "2"].
If the original array contains 0 or "0", then they will not be present in the resulting array.
If resulting array should include only integer numbers,
str.filter(Number.isInteger)
This will exclude the number in the form of string like "1", "2", etc.
For both integer and float numbers,
str.filter(Number.isFinite)

Making a small change to your code to make it work, this might possibly work.
var str = ["https://xx.jpg", "https://xx.jpg", "1", "https://guide.jpg", "2", "/static.jpg"];
var filtered = str.filter(function (item) {
return !(parseInt(item) == item);
});
console.log(filtered);
Or if you want the numbers:
var str = ["https://xx.jpg", "https://xx.jpg", "1", "https://guide.jpg", "2", "/static.jpg"];
var filtered = str.filter(function (item) {
return (parseInt(item) == item);
});
console.log(filtered);

Use isNaN().
var str=["https://xx.jpg","https://xx.jpg","1","https://guide.jpg","2","/static.jpg"];
var filtered = str.filter(function(item) {
return (!isNaN(item));
});
console.log(filtered);

var str = ["https://xx.jpg","https://xx.jpg","1","https://guide.jpg","2", "/static.jpg" ]
str.filter(item=>!isNaN(parseInt(item)))
parseInt convert number to integer and other values converted to "NaN", isNaN function validate value is either "NaN" or not
https://www.w3schools.com/jsref/jsref_isnan.asp
https://www.w3schools.com/jsref/jsref_parseint.asp

You could use a regular expression which test a string, if it contains only digits.
var array = ["https://xx.jpg", "https://xx.jpg", "1", "https://guide.jpg", "2", "/static.jpg"];
array = array.filter(function (a) {
return !/^\d+$/.test(a);
});
console.log(array);

If you want to check if a string only contains numeric digits, you can use regular expressions.
var str = ["https://xx.jpg", "https://xx.jpg", "1", "https://guide.jpg", "2", "/static.jpg"];
var filtered = str.filter(function (item) {
return item.match(/^-?\d+$/);
});
console.log(filtered);

const intArray = [];
const strArray = [];
const rest_test_parameters = (...args) => {
args.filter((item) => {
if (parseInt(item)) {
return intArray.push(parseInt(item));
}
strArray.push(item);
});
};
const objects = {
a: "a",
b: "c"
};
rest_test_parameters(1, 2, "99","hello", objects);
console.log("intArray", intArray);
console.log("strArray",strArray);

You usage func helper in filter
function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n);}

str = str.filter(function(item) {
return (item !== 0) && ((!item) || (isNaN(item)));
});
The right side of the operation calls filter and passes a function which returns true if an item is not 0 and it is either falsey or not a number; otherwise it returns false. For instance "" or null should be kept in the array as far as the specification goes. With this approach we get the desired array and we assign it to the str variable.

const filterNumbers = [123456789, 'limit', 'elite', 987654321, 'destruction', 'present'];
const result = filterNumbers.filter(number => parseInt(number) == number);
console.log(result);
Here's similar code that returns the number instead of the string. The => is just alternative syntax for function and return (see arrow function expressions), but will yield the same result.

Most of the above answers are good, but missing one thing; filtering out array of numbers(neither integer, nor string form of numbers).
I haved added the snippet to address those little issues.
var str = ["https://xx.jpg", "https://xx.jpg", "1", "https://guide.jpg", "2.4", "/static.jpg","4"];
var filteredNumbers = str.filter(item=> parseFloat(item) == item).map(item=>parseFloat(item));
console.log(filteredNumbers);

Here's a one liner:
arr.filter(n => (parseInt(n)===0 || +n)).map(Number)
This is assuming it is a flat array and not a nested one.

Related

Javascript filter out substring elements in an array

Is there a way, ideally using higher order functions, to filter out the repeating substring elements in an array? For example:
var obj = ["a", "a.b.c", "a.b", "a.e", "a.b.d"]
to become
["a.b.c", "a.e", "a.b.d"] //since both "a" and "a.b" appear inside either "a.b.c" or "a.b.d".
The solution will probably require Hashtables or Sets but I am not sure how to get started.
Can use a filter() and find() combination along with a Set to remove duplicates
var data = ["a", "a.b.c", "a.b", "a.e", "a.b.d"];
var res = [...new Set(data)].filter(val => !data.find(s => s !== val && s.startsWith(val)));
console.log(res)
You could use the array .reduce function to do this.
Just see if your current string is a substring of something already in the array, and ignore it if so. Otherwise, if something in the array is a substring of the current string, replace it. And finally, if neither is the case, add the current string to the array:
var obj = ["a", "a.b.c", "a.b", "a.e", "a.b.d"]
var result = obj.reduce((deduped, item) => {
if (deduped.some(s => s.includes(item))) return deduped;
const replace = deduped.findIndex(s => item.includes(s));
if (replace !== -1) {
deduped.splice(replace, 1, item)
} else {
deduped.push(item)
}
return deduped;
}, []);
console.log(result)
An alternative is using the function filter to get the desired elements, the function some to check at least one match and the function includes to check if the current element is a substring.
This approach finds a substring to identify a match.
var obj = ["a", "a.b.c", "a.b", "a.e", "a.b.d"],
filtered = obj.filter((element, i, arr) => !arr.some((o, oi) => {
return oi === i ? false : o.includes(element);
}));
console.log(filtered);
.as-console-wrapper { max-height: 100% !important; top: 0; }

How to parse a string into an array

If a have a string in this format:
$parsethis = 'string[1][2]';
How do I parse it so my result is an array like:
$parsed = ['string', 1 , 2]
I think REGEX is the way to go here, in compiination with the Arrays split method.
var array = $parsed.split(/\]\[|\[|\]/);
console.log(array) results in
Array [ "string", "1", "2", "" ]
iam not very good at using regular expressions, but maybe this is leading you in the right direction.
You can do something like this:
var $parsethis = 'string[1][2]';
var arr = $parsethis.replace(/\]/g,'').split('[');
//arr = ["string", "1", "2"]
alert(arr); //alerts "string,1,2"
The arr array will be all strings, though. Based on the question, I do not know how you will be using the results.
You can get an array from that string using str.split(), and then cleaning it up with str.replace().
var parsed = parsethis.split('[');
console.log(parsed); // ["string", "1]", "2]"]
for(var i = 0; i++; i<parsed.length){
parsed[i] = parsed[i].replace(']','');
}
console.log(parsed); // ["string", "1", "2"]

Underscore return indeces of objects in an array where word exists in sentences within objects

I have an array with arrays inside like this;
var lines = [
["1","1","1","A man is walking."]
,["1","1","2","Noooo he's not, no way!"],
["1","1","3","You can't see that far can you?"],
["1","1","4","I can, he stopped, he's looking right at us"]
];
And with Underscore I can get an array inside "lines" if line[4] is exactly the search sentence, like, "A man is walking." would return lines[0];
So I want to be able to search through these sentences(lines) with just a word(s), like "Walking" should match and return the first array in 'lines' since there's a sentence that contains the word.
_.some(lines, function(array){
var result = (array[4] == 'walking' && array[4]);
if (result !== false){
console.log(result);
}
});
How do I modify this underscore function, or if there's a correct one I should use or if at all, even if its something without underscore, please suggest.
Assuming you don't have the luxury of ES6's find, in plain javascript:
var lines = [
["1","1","1","A man is walking."],
["1","1","2","Noooo he's not, no way!"],
["1","1","3","You can't see that far can you?"],
["1","1","4","I can, he stopped, he's looking right at us"]
];
function lineSearch(arr, term) {
var indices = arr.map(function(innerArr, index) {
return innerArr[3].indexOf(term) > -1 ? index : null;
}).filter(function(x) {
return x !== null;
});
var results = arr.map(function(innerArr, index) {
return innerArr[3].indexOf(term) > -1 ? innerArr : null;
}).filter(function(x) {
return x !== null;
});
return {indices: indices, results: results};
}
console.log(lineSearch(lines, "can"));
should give:
{
indices: [2, 3],
results: [["1", "1", "3", "You can't see that far can you?"], ["1", "1", "4", "I can, he stopped, he's looking right at us"]]
}
_.some returns a boolean. You need to filter the matching results which you get by seeing if the search term is within the string. Indexes start at 0 so you need to check index 3 instead of 4.
Working example:
var lines = [
["1", "1", "1", "A man is walking."],
["1", "1", "2", "Noooo he's not, no way!"],
["1", "1", "3", "You can't see that far can you?"],
["1", "1", "4", "I can, he stopped, he's looking right at us"]
];
var input = document.getElementById('search');
var output = document.getElementById('output');
input.onkeyup = function (event) {
var value = this.value;
var results = _.filter(lines, function (array) {
return array[3].indexOf(value) > -1;
});
var indexes = _.map(results, function(array) {
return lines.indexOf(array);
});
output.innerHTML = '<pre>Indexes: ' + JSON.stringify(indexes) + '</pre><pre>' + JSON.stringify(results, null, 2) + '</pre>';
};
<script src="//cdn.jsdelivr.net/lodash/2.1.0/lodash.compat.js"></script>
<input type="text" id="search" placeholder="Search">
<output id="output"></output>

Converting JavaScript object with numeric keys into array

I have an object like this coming back as a JSON response from the server:
{
"0": "1",
"1": "2",
"2": "3",
"3": "4"
}
I want to convert it into a JavaScript array like this:
["1","2","3","4"]
Is there a best way to do this? Wherever I am reading, people are using complex logic using loops. So are there alternative methods to doing this?
It's actually very straight forward with jQuery's $.map
var arr = $.map(obj, function(el) { return el });
FIDDLE
and almost as easy without jQuery as well, converting the keys to an array and then mapping back the values with Array.map
var arr = Object.keys(obj).map(function(k) { return obj[k] });
FIDDLE
That's assuming it's already parsed as a javascript object, and isn't actually JSON, which is a string format, in that case a run through JSON.parse would be necessary as well.
In ES2015 there's Object.values to the rescue, which makes this a breeze
var arr = Object.values(obj);
var json = '{"0":"1","1":"2","2":"3","3":"4"}';
var parsed = JSON.parse(json);
var arr = [];
for (var x in parsed) {
arr.push(parsed[x]);
}
console.log(arr)
Hope this is what you're after!
You simply do it like
var data = {
"0": "1",
"1": "2",
"2": "3",
"3": "4"
};
var arr = [];
for (var prop in data) {
arr.push(data[prop]);
}
console.log(arr);
DEMO
There is nothing like a "JSON object" - JSON is a serialization notation.
If you want to transform your javascript object to a javascript array, either you write your own loop [which would not be that complex!], or you rely on underscore.js _.toArray() method:
var obj = {"0":"1","1":"2","2":"3","3":"4"};
var yourArray = _(obj).toArray();
Nothing hard here. Loop over your object elements and assign them to the array
var obj = {"0":"1","1":"2","2":"3","3":"4"};
var arr = [];
for (elem in obj) {
arr.push(obj[elem]);
}
http://jsfiddle.net/Qq2aM/
var JsonObj = {
"0": "1",
"1": "2",
"2": "3",
"3": "4"
};
var array = [];
for (var i in JsonObj) {
if (JsonObj.hasOwnProperty(i) && !isNaN(+i)) {
array[+i] = JsonObj[i];
}
}
console.log(array)
DEMO
Try this:
var newArr = [];
$.each(JSONObject.results.bindings, function(i, obj) {
newArr.push([obj.value]);
});
You can use Object.assign() with an empty array literal [] as the target:
const input = {
"0": "1",
"1": "2",
"2": "3",
"3": "4"
}
const output = Object.assign([], input)
console.log(output)
If you check the polyfill, Object.assign(target, ...sources) just copies all the enumerable own properties from the source objects to a target object. If the target is an array, it will add the numerical keys to the array literal and return that target array object.
var obj = {"0":"1","1":"2","2":"3","3":"4"};
var vals = Object.values(obj);
console.log(vals); //["1", "2", "3", "4"]
Another alternative to the question
var vals = Object.values(JSON.parse(obj)); //where json needs to be parsed
Using raw javascript, suppose you have:
var j = {0: "1", 1: "2", 2: "3", 3: "4"};
You could get the values with:
Object.keys(j).map(function(_) { return j[_]; })
Output:
["1", "2", "3", "4"]
Not sure what I am missing here but simply trying the below code does the work. Am I missing anything here?
https://jsfiddle.net/vatsalpande/w3ew5bhq/
$(document).ready(function(){
var json = {
"code" :"1",
"data" : {
"0" : {"id":"1","score":"44"},
"1" : {"id":"1","score":"44"}
}
};
createUpdatedJson();
function createUpdatedJson(){
var updatedJson = json;
updatedJson.data = [updatedJson.data];
$('#jsondata').html(JSON.stringify(updatedJson));
console.log(JSON.stringify(updatedJson));
}
})
Assuming your have a value like the following
var obj = {"0":"1","1":"2","2":"3","3":"4"};
Then you can turn this into a javascript array using the following
var arr = [];
json = JSON.stringify(eval('(' + obj + ')')); //convert to json string
arr = $.parseJSON(json); //convert to javascript array
This works for converting json into multi-diminsional javascript arrays as well.
None of the other methods on this page seemed to work completely for me when working with php json-encoded strings except the method I am mentioning herein.
Here is an example of how you could get an array of objects and then sort the array.
function osort(obj)
{ // map the object to an array [key, obj[key]]
return Object.keys(obj).map(function(key) { return [key, obj[key]] }).sort(
function (keya, keyb)
{ // sort(from largest to smallest)
return keyb[1] - keya[1];
}
);
}
This is best solution. I think so.
Object.keys(obj).map(function(k){return {key: k, value: obj[k]}})
The accepted solution expects the keys start from 0 and are continuous - it gets the values into the array, but looses the indexes on the way.
Use this if your "object with numerical keys" does not fulfill those stricter assumptions.
//let sourceObject = ...
let destinationArray = [];
Object.keys(sourceObject).forEach(k => destinationArray[k] = sourceObject[k]);
var data = [];
data = {{ jdata|safe }}; //parse through js
var i = 0 ;
for (i=0;i<data.length;i++){
data[i] = data[i].value;
}
You can convert json Object into Array & String using PHP.
$data='{"resultList":[{"id":"1839","displayName":"Analytics","subLine":""},{"id":"1015","displayName":"Automation","subLine":""},{"id":"1084","displayName":"Aviation","subLine":""},{"id":"554","displayName":"Apparel","subLine":""},{"id":"875","displayName":"Aerospace","subLine":""},{"id":"1990","displayName":"Account Reconciliation","subLine":""},{"id":"3657","displayName":"Android","subLine":""},{"id":"1262","displayName":"Apache","subLine":""},{"id":"1440","displayName":"Acting","subLine":""},{"id":"710","displayName":"Aircraft","subLine":""},{"id":"12187","displayName":"AAC","subLine":""}, {"id":"20365","displayName":"AAT","subLine":""}, {"id":"7849","displayName":"AAP","subLine":""}, {"id":"20511","displayName":"AACR2","subLine":""}, {"id":"28585","displayName":"AASHTO","subLine":""}, {"id":"45191","displayName":"AAMS","subLine":""}]}';
$b=json_decode($data);
$i=0;
while($b->{'resultList'}[$i])
{
print_r($b->{'resultList'}[$i]->{'displayName'});
echo "<br />";
$i++;
}

How to check if a string contains text from an array of substrings in JavaScript?

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))

Categories