How to check an array if it contains a string in Javascript? - javascript

I have an array that contains string.
var js_userBoxName = new Array();
I want to search the elements of the array if a string has the word "foo" it should displayed.
So for example my array contains the words {foofy, foofa, foo, awtsy}, foofy, foofa and foo will be displayed since they all contains the word foo.

Check out the Array.filter method:
var arr = ['foofy', 'foofa', 'foo', 'awtsy'];
var fooItems = arr.filter(function (item) {
return item.indexOf('foo') >= 0;
});
// Yields ['foofy', 'foofa', 'foo']
The linked MDN page contains a polyfill for browsers that do not support it. If you happen to be using jQuery, you could use $.grep:
var arr = ['foofy', 'foofa', 'foo', 'awtsy'];
var fooItems = $.grep(arr, function (item) {
return item.indexOf('foo') >= 0;
});

You could also try this:
var myarray = ["foofy", "foofa", "foo", "awtsy"];
var searched_string = "foo";
var foundmatch = [];
for(i=0; i < myarray.length; i++){
if(myarray[i].match(searched_string)){
foundmatch.push(myarray[i]);
}
}
alert(foundmatch);

NOTE: Good performance tip is to always cache the length of your array when iterating over it rather than recalculating it for each loop execution. len = js_userBoxName.length
http://jsperf.com/caching-array-length/4
function () {
for(var i = 0, len = js_userBoxName.length; i < len; i++){
if(typeof js_userBoxName[i] === 'string'){
if(js_userBoxName[i].indexOf('foo') == -1)
return true;
}
}
return false;
}

The following function should do the trick, it uses only standard acme script elements
function Find (myarray, searchterm){
for (var i=0, len = myarray.length; i<len; i += 1){
if (typeof(myarray[i]) === 'string' && myarray[i].search(searchterm) !== -1){
// print or whatever
//hint use a callback here that you pass in as an additional arugment
}
}
}
using search allows you to use regex if you need to check for something more complex

The following should work:
var myArray = ['foofy', 'foofa', 'foo', 'awtsy'];
for ( var i = 0; i < myArray.length; i++ ) {
if ( myArray[i].contains('foo') )
console.log(myArray[i]);
}
prints:
foofy
foofa
foo
Note: "awtsy" does not contain the pattern foo

Related

Creating a frequency listing of characters

charFreq function that's not quite working out. Hit a wall. I know I may need to
do a conditional. Calling the function returns an Object error. I'm attempting
to get string into an empty object displaying the characters like this - Object
{o: 4, p: 5, z: 2, w: 4, y: 1…}. New to Javascript by the way.
Just realized I shouldn't be appending anything. Do I need to do a .push() to
push the array into the object?
function charFreq (string){
var emptyObj = {};
for(var i = 0; i < string.length; i++) {
// console.log(string.charAt(i));
var args = [string.charAt(i)];
var emptyArr = [''].concat(args);
emptyObj += emptyArr
}
return emptyObj
}
undefined
charFreq('alkdjflkajdsf')
"[object Object],a,l,k,d,j,f,l,k,a,j,d,s,f"
You just need to set emptyObj's key of that specific letter to either 1 if it doesn't exist or increment the count if it already does.
function charFreq(string) {
var obj = {};
for (var i = 0; i < string.length; i++) {
if (!obj.hasOwnProperty(string[i])) {
obj[string[i]] = 1;
} else {
obj[string[i]]++;
}
}
return obj;
}
console.log(charFreq('alkdjflkajdsf'));
Try this instead: you need to create an object property first, then increment it. What you do, is implicitly convert the object to a string and concatenate more string data to it (using += and concat).
This is a simple approach:
function charFreq(string){
var emptyObj={};
for(var i=0; i<string.length; i++) {
if(!emptyObj.hasOwnProperty(string[i])){ // if property doesn’t exist
emptyObj[string[i]]=0; // create it and set to 0
}
emptyObj[string[i]]++; // increment it
}
return emptyObj;
}
A modified version of Richard Kho's code:
function charFreq(string) {
var obj = {};
for (var i = 0; i < string.length; i++) {
var c=string[i];
if (c=='') continue;
if (obj[c]==null) obj[c]=0;
obj[c]++;
}
return obj;
}

Explode and process values as an array using Javascript [duplicate]

So, I have a string with the delimiter | , one of the sections contains "123", is there a way to find this section and print the contents?
something like PHP explode (but Javascript) and then a loop to find '123' maybe? :/
const string = "123|34|23|2342|234";
const arr = string.split('|');
for(let i in arr){
if(arr[i] == 123) alert(arr[i]);
}
Or:
for(let i in arr){
if(arr[i].indexOf('123') > -1) alert(arr[i]);
}
Or:
arr.forEach((el, i, arr) => if(arr[i].indexOf('123') > -1) alert(arr[i]) }
Or:
arr.forEach((el, i, arr) => if(el == '123') alert(arr[i]) }
Or:
const arr = "123|34|23|2342|234".split('|')
if(arr.some(el=>el == "123")) alert('123')
More information on string and Array memeber functions.
You can use split() in JavaScript:
var txt = "123|1203|3123|1223|1523|1243|123",
list = txt.split("|");
console.log(list);
for(var i=0; i<list.length; i++){
(list[i]==123) && (console.log("Found: "+i)); //This gets its place
}
LIVE DEMO: http://jsfiddle.net/DerekL/LQRRB/
This should do it:
var myString = "asd|3t6|2gj|123hhh", splitted = myString.split("|"), i;
for(i = 0; i < splitted.length; i++){ // You could use the 'in' operator, too
if(splitted[i].match("123")){
// Do something
alert(splitted[i]); // Alerts the entire contents between the original |'s
// In this case, it will alert "123hhh".
}
}
.split is the equivalent of explode, whereas .join is the equivalent of implode.
var myString = 'red,green,blue';
var myArray = myString.split(','); //explode
var section = myArray[1];
var myString2 = myArray.join(';'); //implode

Count how many strings in an array have duplicates in the same array [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Array value count javascript
I have an array which contains several duplicates, what I'm trying to achieve is to count how many duplicates each unique string has in this one array.
The array looks something like this
array = ['aa','bb','cc','aa','ss','aa','bb'];
Thus I would like to do something like this
if (xWordOccurrences >= 5) {
// do something
}
But I'm not sure how I would code this.
I was thinking, create an object with each unique string, then loop through the original array, match each string with it's object and increment it's number by 1, then loop over the object to see which words had the most duplicates...
But this seems like an over complexe way to do it.
You can use an object which has keys of the Array's values and do something like this
// count everything
function getCounts(arr) {
var i = arr.length, // var to loop over
obj = {}; // obj to store results
while (i) obj[arr[--i]] = (obj[arr[i]] || 0) + 1; // count occurrences
return obj;
}
// get specific from everything
function getCount(word, arr) {
return getCounts(arr)[word] || 0;
}
getCount('aa', ['aa','bb','cc','aa','ss','aa','bb']);
// 3
If you only ever want to get one, then it'd be more a bit more efficient to use a modified version of getCounts which looks similar to getCount, I'll call it getCount2
function getCount2(word, arr) {
var i = arr.length, // var to loop over
j = 0; // number of hits
while (i) if (arr[--i] === word) ++j; // count occurance
return j;
}
getCount2('aa', ['aa','bb','cc','aa','ss','aa','bb']);
// 3
Try this function:
var countOccurrences = function(arr,value){
var len = arr.length;
var occur = 0;
for(var i=0;i<len;i++){
if(arr[i]===value){
occur++;
}
}
return occur;
}
var count = countOccurrences(['aaa','bbb','ccc','bbb','ddd'],'bbb'); //2
If you want, you can also add this function to the Array prototype:
Array.prototype.countOccurrences = function(value){
var len = this.length;
var occur = 0;
for(var i=0;i<len;i++){
if(this[i]===value){
occur++;
}
}
return occur;
}
How about you build an object with named property?
var array = ['aa','bb','cc','aa','ss','aa','bb'];
var summary = {};
var item = '';
for ( i in array){
item = array[i];
if(summary[item]){
summary[item] += 1;
}
else{
summary[item] = 1;
}
}
console.log( summary );
summary will contain like this
{aa: 3, bb: 2, cc: 1, ss: 1}
which you could then iterate on and then sort them later on if needed.
finally to get your count, you could use this summary['aa']
<script type="text/javascript">
var array = ['aa','bb','cc','aa','ss','aa','bb'];
var myMap = {};
for(i = 0; i < array.length; i++) {
var count = myMap[array[i]];
if(count != null) {
count++;
} else {
count = 1;
}
myMap[array[i]] = count;
}
// at this point in the script, the map now contains each unique array item and a count of its entries
</script>
Hope this solves your problem
var array = ['aa','bb','cc','aa','ss','aa','bb'];
var dups = {};
for (var i = 0, l = array.length; i < l; i++ ) {
dups[array[i]] = [];
}
for (str in dups) {
for (var i = 0, l = array.length; i < l; i++ ) {
if (str === array[i]) {
dups[str].push(str);
}
}
}
for (str in dups) {
console.log(str + ' has ' + (dups[str].length - 1) + ' duplicate(s)');
}
This function may do everything you need.
function countDupStr(arr, specifier) {
var count = {}, total = 0;
arr.forEach(function (v) {
count[v] = (count[v] || 0) + 1;
});
if(typeof specifier !== 'undefined') {
return count[specifier] - 1;
}
Object.keys(count).forEach(function (k) {
total += count[k] - 1;
});
return total;
}
Each value in the array is assigned and incremented to the count object. Whether or not a specifier was passed, the function will return duplicates of that specific string or the total number of duplicates. Note that this particular technique will only work on string-coercible values inside your arrays, as Javascript can only index objects by string.
What this means is that during object assignment, the keys will normalize down to strings and cannot be relied upon for uniqueness. That is to say, this function wouldn't be able to discern the difference between duplicates of 3 and '3'. To give an example, if I were to perform:
var o = {}, t = {};
o[t] = 1;
console.log(o);
The key used in place of t would eventually be t.toString(), thus resulting in the perhaps surprising object of {'[object Object]': 1}. Just something to keep in mind when working with Javascript properties.
I saw this post about it, perhaps it can help:
http://ryanbosinger.com/blog/2011/javascript-count-duplicates-in-an-array/

Javascript: loop through all records within an object with an irregular key

UPDATED
I've got an object var myObject = {};
I build it using a key like so:
myObject[key] = {
name: ...
};
So imagine I have created three records:
myObject[13] = {...};
myObject[281] = {...};
myObject[76] = {...};
I now want to loop through the object as if it were an array.
var i,
length = myObject.length; // ?? Problem here 'cos it ain't an array
for (i = 0; i < length; i += 1) {
????
};
How can I refer to the three elements at ????? I don't know the numbers 13, 281 & 76, and myObject[0] is not going to find the first record.
Thanks.
You shouldn't be using an array if your keys aren't consecutive. Use an object instead:
var myObject = {};
To loop over an object's keys, you use the for..in syntax:
for (var key in myObject) {
var value = myObject[key];
}
To make your current code work, you'd have to loop over all of the keys and check to see if they have values:
for (var i = 0; i < myArray.length; i++) {
var value = myArray[i];
if (typeof value === 'undefined') continue;
console.log(key, ' -> ', value)
}
If you're using a modern JavaScript engine:
myArray.forEach(function(val, key) {
// val = the value
// key = the index
});
And that's it. To get its size (3, in this case)...
var size = myArray.reduce(function(prev) {
return ++prev;
}, 0);
If you want this to work in older browsers, you'll need to do something else. The easiest solution would probably be to implement something like this yourself:
for (var i = 0; i < myArray.length; i ++) {
var val = myArray[i];
if (typeof val !== "undefined") {
console.log(val);
}
}
To get its size, it's a similar endeavor (that you could combine with the above method if you're doing both):
var size = 0;
for (var i = 0; i < myArray.length; i ++) {
if (typeof myArray[i] !== "undefined")
size ++;
}
If you want to use forEach and reduce like the above, you'll need to find a shim (basically, you'll need to implement those functions yourself). I'd recommend the larger of the two forEach shims on this page and the reduce shim on this page, or use a library that shims them all.

Remove duplicate element pairs from multidimensional array

I have an array that looks like this:
1. coordinates = [ [16.343345, 35.123523],
2. [14.325423, 34.632723],
3. [15.231512, 35.426914],
4. [16.343345, 35.123523],
5. [15.231512, 32.426914] ]
The latitude on line 5 is the same as on line 3, but they have different longitudes and are therefore not duplicates.
Both the latitude and longitude are the same on line 3 and 6, and are therefore duplicates and one should be removed.
The difficulty in this question that different arrays never compare equal even if they contain same values. Therefore direct comparison methods, like indexOf won't work.
The following pattern might be useful to solve this. Write a function (or use a built-in one) that converts arrays to scalar values and checks if these values are unique in a set.
uniq = function(items, key) {
var set = {};
return items.filter(function(item) {
var k = key ? key.apply(item) : item;
return k in set ? false : set[k] = true;
})
}
where key is a "hash" function that convert items (whatever they are) to comparable scalar values. In your particular example, it seems to be enough just to apply Array.join to arrays:
uniqueCoords = uniq(coordinates, [].join)
You can use standard javascript function splice for this.
for(var i = 0; i < coordinates.length; i++) {
for(var j = i + 1; j < coordinates.length; ) {
if(coordinates[i][0] == coordinates[j][0] && coordinates[i][1] == coordinates[j][1])
// Found the same. Remove it.
coordinates.splice(j, 1);
else
// No match. Go ahead.
j++;
}
}
However, if you have thousands of points it will work slowly, than you need to consider to sort values at first, then remove duplicates in one loop.
I rewrote the answer from thg435 (It does not allow me to post comments) and prototype it also using jQuery instead, so this will work on all browsers using it (Even IE7)
Array.prototype.uniq = function (key) {
var set = {};
return $.grep(this, function (item) {
var k = key
? key.apply(item)
: item;
return k in set
? false
: set[k] = true;
});
}
You can use it like:
arr = arr.uniq([].join);
If you are not on Safari this single liner could do the job
var arr = [[16.343345, 35.123523],
[14.325423, 34.632723],
[15.231512, 35.426914],
[16.343345, 35.123523],
[15.231512, 32.426914]],
lut = {},
red = arr.filter(a => lut[a] ? false : lut[a] = true);
document.write("<pre>" + JSON.stringify(red,null,2) + "</pre>");
It might be simpler to create another array keeping only unique coordinate pairs
var uniqueCoors = [];
var doneCoors = [];
for(var x = 0; x < coordinates.length; x++) {
var coorStr = coordinates[x].toString();
if(doneCoors.indexOf(coorStr) != -1) {
// coordinate already exist, ignore
continue;
}
doneCoors.push(coorStr);
uniqueCoors.push(coordinates[x]);
}
function sortCoordinates(arr){
var obj = {};
for(var i = 0, l = arr.length; i < l; i++){
var el = arr[i];
var lat = el[0];
var lng = el[1];
if(!obj[lat + lng]){
obj[lat + lng] = [lat, lng];
}
}
var out = [];
for(p in obj){
out.push([obj[p][0], obj[p][1]]);
}
return out;
}
I am not sure about coordinates[][] dataType. Make the comparison accordingly.
var dubJRows= new Array();
for(int i = 0; i < coordinates.length -2; i++){
for(int j = i+1; j < coordinates.length -1; j++){
if (i != j && chk_dubJRows_not_contains(j)) {
innerArray1 [1][1] = coordinates[i];
innerArray2 [1][1] = coordinates[j];
if ( innerArray1 [1][0] == innerArray2[1][0]
&& innerArray1[1][1] == innerArray2[1][1]) {
dubJRows.push(j);
}
}
}
}
//REMOVE ALL dubJRows from coordinates.

Categories