Split multiple arrays into strings, skipping empty arrays - javascript

I've made an AJAX call that has returned 20 arrays, some of which are empty, and others that have one or more items in them. I've split each array into strings using a for loop. The only problem is that this creates lots of empty strings from the arrays that were empty. Is there a way that I could skip the empty arrays in my for loop?
success: function(data){
console.log(data);
for(x in data.data){
var hashArray = data.data[x].tags;
var hashStrings = hashArray.toString().split(',');
var hashtags = '';
for(var i = 0; i < hashStrings.length; i++) {
hashtags = hashStrings[i];
console.log(hashtags);
}
}
}

Check the .length of the array. If it's 0 then it contains no elements, in which case continue to the next loop iteration. EDIT per comments for the array we're testing, seems more likely you'll be testing data.data[x].tags.length:
success: function(data){
console.log(data);
for(x in data.data){
if (data.data[x].tags.length == 0) continue;
var hashArray = data.data[x].tags;
var hashStrings = hashArray.toString().split(',');
var hashtags = '';
for(var i = 0; i < hashStrings.length; i++) {
hashtags = hashStrings[i];
console.log(hashtags);
}
}
}

Related

Trying to create an array of duplicate values from another array, why doesn't my code work?

I am working on this piece of code here where the goal is to create an array of all the values that are duplicated from another array. The resulting array I'd like to have should only enter the duplicated values from the first array once. The catch is I can't use any array functions or methods. This is what I have so far:
var numbers = [8,24,20,5,13,3,1,12,11,24,8,24,20,4,5,23,24,23,21,2,19,3,21,2,14,17,21,5,7,10,20,11,0,5,18,2,13,11,14,3,20,1,23,6,21,10,14,0,15,20];
var results = [];
var tempArr = [];
for (var i = 0; i <= numbers.length; i++) {
if (tempArr[numbers[i]] === undefined) {
tempArr[numbers[i]] = 1;
} else if (results[numbers[i]] === undefined) {
results.push(numbers[i]);
}
}
console.log(tempArr);
console.log(results);
I am getting closer to me desired output… but for some reason the results array continues to contain multiple entries of the values that are duplicated in the numbers array. Where am I going wrong here?
You're basically abusing an array as an object. Try using an object instead to log your values (and give said object a name that represents what it holds), it'll greatly simplify your code:
var numbers = [8,24,20,5,13,3,1,12,11,24,8,24,20,4,5,23,24,23,21,2,19,3,21,2,14,17,21,5,7,10,20,11,0,5,18,2,13,11,14,3,20,1,23,6,21,10,14,0,15,20];
var results = [];
var seenValues = {};
for (var i = 0; i < numbers.length; i++) {
const number = numbers[i];
seenValues[number] = 1 + (seenValues[number] || 0);
// check to see if it's been seen exactly once before,
// so that the duplicated value is only added once:
if (seenValues[number] === 2) results[results.length] = number;
}
//console.log(seenValues);
console.log(results);

How to take First letter from the string with comma separated?

I have one array and I store comma separated strings in the array. Now I want to take in the string every first letter take from the string with comma separated.
For ex => Abc, Xyz, Hji so now I want A, X, H.
Here below listed my code and array.
This is my code =>
var ArryString = [];
for (var i = 0; i < data.length; i++) {
ArryString.push(data[i].Str);
}
Current o/p =>
"Abc"
"Xyz,Hji,Lol",
"Uyi,Mno"
my expacted o/p= >
"A"
"X,H,L"
"U,M"
You could split the strings and take only the first character with a destructuring assignment and join the first characters for a string. Then map the new string for a new array.
var data = ["Abc", "Xyz,Hji,Lol", "Uyi,Mno"];
result = data.map(s => s
.split(',')
.map(([c]) => c)
.join());
console.log(result);
This is not looking good and amateurish but understandable.
var ArryString = [];
var data = ["Abc", "Xyz,Hji,Lol", "Uyi,Mno"];
var index=0;
for (var k in data){
var a=data[k].split(",");
ArryString[index]=a[0].charAt(0);
if(a.length > 1)
for (var l=1 ;l<a.length ; l++)
ArryString[index]+=","+a[l].charAt(0);
index++;
}
console.log(ArryString);
You can use charAt method Return the first character of a string.
var newString = [];
for (var i=0; i< newString.length; i++)
{
newString.push(ArrayString[i].charAt(0);
}
Here is a working example :
// We've got an array of comma separated worlds
// Sometimes we've got one, sometimes several
data=["Hello","i","have","one,array","and,i","store","comma,separated,string,in","the","array"];
// We want to ouput the same pattern but keeping the initial letter only
var result = [];
var items = [];
var aChar;
// We loop thru the data array
for (var i = 0; i < data.length; i++) {
// We make a small array with the content of each cell
items = data[i].split(",");
for (var j = 0; j < items.length; j++) { // We loop thru the items array
aChar = items[j].charAt(0); // We take the first letter only
if (aChar!="") // If the item/work was not empty the we keep only the initial letter in our items array
items[j] = aChar;
}
result.push(items.join(",")); // we store comma separated first letters in our result array
}
console.log(result)
Use the String.charAt() method for each string in the array and push the first character to a new array.
Example function:-
function takeFirstChar(arr){
var new_arr = [];
arr.forEach(function(el){
var firstLetter = el.charAt(0)
new_arr.push(firstLetter);
});
return new_arr;
}
takeFirstChar(['hello','cruel','world']);
//Output-> ['h','c','w']

JavaScript: Iterating through multi-dimensional arrays and extracting multiple search values

What I want to do:
Search through a multi-dimensional array using multiple search strings.
Example of what I am currently doing:
var multiArray = [['Apples and pears', 'tuna salad'],['bananas tuna'],['the colour blue']];
var singleArray = [];
var match_array = [];
// Turn multiple arrays into one big one
for (var i = 0; i < multiArray.length; i++) {
for (var x = 0; x < multiArray[i].length; x++) {
singleArray.push(multiArray[i][x]);
}
}
// Create a new array from matched strings
function find_match(to_match) {
for (var i in singleArray) {
if (singleArray[i].indexOf(to_match)!= -1)
match_array.push(singleArray[i]);
}
return (match_array.length === 0 ? null : match_array);
}
// Find matching terms for match_array
find_match('tuna');
find_match('the');
alert(match_array);
JSFiddle Demo
Questions:
Obviously this is a cluttered way of doing this. How can this be
streamlined(i.e. searching the multiArray directly and not using
multiple find_match functions)?
How can I get only the exact string matches, preferably without breaking up the multi-dimensional array?
What are your thoughts about searching through massive
multidimensional arrays?
Do you want something like this?
var multiArray = [['Foo', 'Bar'],['Foo'],['Bar']];
var singleArray = [];
var match_array = [];
// Turn multiple arrays into one big one
for (var i = 0; i < multiArray.length; i++) {
for (var x = 0; x < multiArray[i].length; x++) {
singleArray.push(multiArray[i][x]);
}
}
// Create a new array from matched strings
function find_match(to_match, where_search) {
for (var j in where_search) {
if(where_search[j] instanceof Array){
find_match(to_match, where_search[j]);
}else{
for (var i in to_match) {
if (where_search[j].indexOf(to_match[i]) ==0 &&
where_search[j].length == to_match[i].length)
match_array.push(where_search[j]);
}
}
}
return (where_search.length === 0 ? null : match_array);
}
// Find matching terms for match_array
find_match(['Foo', 'Bar'],multiArray);
alert(match_array);

jQuery iterate through loop delete elements

I have a javascript array of objects: each object contains key/value pairs. I'm trying to iterate through this array, and delete any object whose value for a particular key (say "Industry") fails to match a given value. Here is my code, for some reason it's not looping through the whole array, and I think it has something to do with the fact that when I delete an item the loop counter is botched somehow:
var industry = 'testing';
var i = 0;
for (i = 0; i < assets_results.length; i++) {
var asset = assets_results[i];
var asset_industry = asset['industry'];
if (industry != asset_industry) { assets_results.splice(i,1); }
}
Any ideas? Thanks in advance.
This is because when you splice one element, the size of array decreases by one. All elements after the splice shift one position to the beginning of the array and fills the space of spliced one. So the code misses one element.Try this code.
var industry = 'testing';
var i = 0;
for (i = 0; i < assets_results.length; i++) {
var asset = assets_results[i];
var asset_industry = asset['industry'];
if (industry != asset_industry) {
assets_results.splice(i,1);
i--;
}
}
This is a common problem when modifying an object while iterating through it. The best way to avoid this problem is, rather than deleting pairs from the existing array if they fail the test, to create a new array and only add pairs if they pass the test.
var industry = 'testing';
var i = 0;
var asset_results_filtered = [];
for (i = 0; i < assets_results.length; i++) {
if (industry == assets_results[i]) {
asset_results_filtered.push(assets_results[i]);
}
}
EDIT: Your code looked a bit illogical — I modified the example to use the variables given.
splice removes an element from an array and resizes it :
var arra = ['A', 'B', 'C', 'D'];
arr.splice(1,2); // -> ['A', 'D'];
Which means that you should not increment i when you splice, because you skip the next element. splicing will make of the i + 2 element the i + 1 element.
var industry = 'testing';
for (var i = 0, max = assets_results.length; i < max; ) { // Accessing a property is expensive.
if (industry != assets_results[i]['industry']) {
assets_results.splice(i,1);
} else {
++i;
}
}
Try this instead:
var industry = 'testing';
var i = assets_results.length - 1;
for (; i > 0; i--) {
var asset = assets_results[i],
asset_industry = asset['industry'];
if (industry != asset_industry) { assets_results.splice(i,1); }
}

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/

Categories