Hi i have this function below that removes duplicates from the variable suggest but sometimes the data i receive for the suggest variable is empty and the code below wont work beacause of the JSON.parse function how do i make it so that the variable accepts empty data so that the code below will still run without any problems. Any help would be appreciated thanks!
function suggestData(data){
var suggest = []; // I tried adding this and setting it to null but it doesn't seem to work.
suggest = JSON.parse(data);
for (var i = suggest.length - 1; i >= 0; i--) {
for (var j = 0; j < arrString.length; j++) {
if (suggest[i] === arrString[j]) {
suggest.splice(i, 1);
}
}
}
You can set suggest inside an if condition to check whether data exists or not
function suggestData(data){
var suggest = [];
if(data){
suggest = JSON.parse(data);
}
for (var i = suggest.length - 1; i >= 0; i--) {
for (var j = 0; j < arrString.length; j++) {
if (suggest[i] === arrString[j]) {
suggest.splice(i, 1);
}
}
}
Also you can simply end the function if you do not want to execute it when data is empty:
function suggestData(data) {
if(!data){
return false;
}
//other code here
...
}
Set the length conditionally as,
var length = suggest? suggest.length: 0;
function suggestData(data){
var suggest = [];
suggest = JSON.parse(data);
var length = suggest? suggest.length: 0;
for (var i = length - 1; i >= 0; i--) {
for (var j = 0; j < arrString.length; j++) {
if (suggest[i] === arrString[j]) {
suggest.splice(i, 1);
}
}
}
}
suggestData(null);
function suggestData(data){
var suggest = []; // I tried adding this and setting it to null but it doesn't seem to work.
if(data)
suggest = JSON.parse(data);
for (var i = suggest.length - 1; i >= 0; i--) {
for (var j = 0; j < arrString.length; j++) {
if (suggest[i] === arrString[j]) {
suggest.splice(i, 1);
}
}
}
Just add the if condition on parsing line like
written in above code::
if(data)
suggest = JSON.parse(data);
The simplest:
if(!data || !suggest)
return;
let array = [1,2,3,8,3,4,4,5]
const removeDuplicateItems = arr => [...new Set(arr)];
console.log(removeDuplicateItems(array))
If you just want to remove duplicated items in an array, you can instead try Set which is quite handy
Even if array is empty or null, this method removeDuplicateItems will still works
Related
I have a function
$rootScope.getCurrency = function() {
for (var i = 0; i < data.records.length; i++) {
for (var j = 0; j < data.records[i].columns.length; j++
if (data.records[i].columns[j].fieldname == "Currency") {
// Here I want to
// return the values
// if I do something like
return data.records[i].columns[j].value
// the loop exits on the first condition
// and does not iterate over completely. If I put
// return outside of the
// for loops it says i, j are undefined.
// How can I use the value outside of this loop
}
}
}
}
}
I have to use the returned value in my HTML for binding data.
My HTMl looks like:
ng-repeat i in someArray ng-if={{i.type==currency?getCurrency():''}}
Try pushing the values to an array:
$rootScope.getCurrency = function() {
var result = [];
for (var i = 0; i < data.records.length; i++) {
for (var j = 0; j < data.records[i].columns.length; j++
if (data.records[i].columns[j].fieldname == "Currency") {
// Add to array
result.push(data.records[i].columns[j].value);
}
}
}
return result;
}
My web app is taking in arbitrarily large 2D arrays that sometimes look something like this:
var multiArray = [["","","",""],[1,2,3],["hello","dog","cat"],["","","",""]];
I want to write a function to take out every array inside of multiArray that is comprised entirely of quotes. In other words, any array that looks like this:
["","","",""]
should be deleted from multiArray.
I tried writing the following function, but the problem with using splice in a for loop is that splicing will change the length of the array, and I end up trying to access undefined elements. Please help!
Thanks!
Here's the incorrect function I wrote:
function cleanWhitespace(arrayOfArrays) {
var i;
var arrayOfArraysLength = arrayOfArrays.length;
for (i = 0; i < arrayOfArraysLength; i++) {
var cleanedArray = $.grep(arrayOfArrays[i], function(element) {
return element != ""
});
if (cleanedArray.length == 0) {
arrayOfArrays.splice(i, 1);
}
}
return arrayOfArrays;
};
You can use $.grep :
multiArray = $.grep(multiArray, function(v){
return v.join('');
});
Fiddle : http://jsfiddle.net/scZcB/
on the fly:
var multiArray = [["","","",""],[1,2,3],["hello","dog","cat"],["","","",""]];
var outputArr = removeQuoteArrays(multiArray);
console.log(outputArr);
function removeQuoteArrays(arr) {
var outputArr = [];
for (var i = 0; i < arr.length; i++) {
var currArr = arr[i];
var isAllQuotes = true;
for (var j = 0; j < currArr.length; j++) {
if (currArr[j] != "") {
isAllQuotes = false;
break;
}
}
if (!isAllQuotes) {
outputArr.push(currArr);
}
}
return outputArr;
}
Here's a JSFiddle.
Create a new array instead.
// Only add if...
cleanedArray = multiArray.filter(function(arr){
// Some elements are not blank
return arr.some(function(e){ return e !== "" })
})
I added a length check to your function to break out of the loop if the index reaches the array length:
if (i >= arrayOfArrays.length)
break;
Which makes:
function cleanWhitespace(arrayOfArrays) {
var i;
var arrayOfArraysLength = arrayOfArrays.length;
for (i = 0; i < arrayOfArraysLength; i++) {
var cleanedArray = $.grep(arrayOfArrays[i], function(element) {
return element != ""
});
if (cleanedArray.length == 0) {
arrayOfArrays.splice(i, 1);
if (i >= arrayOfArrays.length)
break;
}
}
return arrayOfArrays;
};
var multiArray = [["","","",""],[1,2,3],["hello","dog","cat"],["","","",""]];
function cleanWhitespace(arrayOfArrays) {
for (var i = 0; i < arrayOfArrays.length; i++) {
var emptyElements = 0;
for (var j = 0; j < arrayOfArrays[i].length; j++ ) {
if (arrayOfArrays[i][j] === "") {
emptyElements++;
}
}
if (emptyElements === arrayOfArrays[i].length) {
arrayOfArrays.splice(i, 1);
}
}
return arrayOfArrays;
}
console.log(cleanWhitespace(multiArray));
http://jsfiddle.net/4Jfr9/
I'd like to check which elements are equal in my two arrays, but can't get it working.
This is my code:
for (var i; i < bombs.length; i++) {
for (var j; j < bombsDb.length; j++) {
if (bombs[i].name === bombsDb[j].address) {
console.log(bombs[i].name);
} else {
console.log("non-equal elements");
}
}
}
So the first array contains objects from the google places api and the second one contains data from my database.
Thanks in advance!
You have to initialize i and j;
for (var i = 0; i < bombs.length; i++) {
for (var j = 0; j < bombsDb.length; j++) {
if (bombs[i].name === bombsDb[j].address) {
console.log(bombs[i].name);
} else {
console.log("non-equal elements");
}
}
}
Comparing can also be done using the .not selector from jquery. Check this:
var a = [1,2,3,4,5,6];
var b = [4,5,6,7,8,9];
$(a).not( $(a).not(b).get() ).get();
This will return the following array
[4,5,6]
You are missing the initial assignment to i and j in your for loop.
// here
// v
for (var i = 0; i < bombs.length; i++) {
// your loop
}
This causes the comparision to return false in the first iteration of the loop since undefined < bombs.length always return false, so it will not proceed.
I have an array which im using to loop through divs i have stored in variables... but i want to use the values in the array as part of the variable names i wish to check.
Heres an example of what im trying to do:
var data_one = document.getElementById('test'),
data_two = document.getElementById('test2'),
array = ['one','two'];
for (var i = 0; i < array.length; i++) { //error on this line
if(parseInt(data_+array[i]) < 3){
//do something
}
}
But i get this error Uncaught ReferenceError: data_ is not defined
Is there a way to use the array values to act like the variable name some how?
What about:
var data = [
document.getElementById('test'),
document.getElementById('test2')
];
for (var i = 0; i < data.length; i++) {
if(parseInt(data[i]) < 3){
//do something
}
}
or with an object:
var data = {
'one': document.getElementById('test'),
'two': document.getElementById('test2')
};
for (var i in data) {
if(parseInt(data[i]) < 3){
//do something
}
}
Use eval which evaluates string as javascript code
var data_a = 12;
var b = "a";
alert("data_"+b); // alerts data_a
alert(eval("data_"+b)); // alerts 12
See http://jsfiddle.net/ftGhd/
var data_one = document.getElementById('test'),
data_two = document.getElementById('test2'),
array = ['one','two'];
for (var i = 0; i < array.length; i++) {
eval("var curr_array = data_"+array[i]);
if(parseInt(curr_array) < 3){
//do something
}
}
I'd like to split a string ("1,2,3") and return it as an int array so I wrote the following function:
function stringToIntArray(string) {
var split = {};
split = string.split(',');
var selected = {};
for (var i = 0; i <= split.length; i++) {
selected[i] = split[i];
}
return selected;
}
However split.length is always undefinied. Where's my mistake?
var selected = {};
doesn't build an array but an object, which has no length property.
You can fix your code by replacing it with
var selected = [];
If you want to return an array of numbers, you can change your code to
function stringToIntArray(string) {
var split = string.split(',');
var selected = [];
for (var i = 0; i < split.length; i++) {
selected.push(parseInt(split[i], 10));
}
return selected;
}
Note that I replaced <= with < in your loop.
Note also that for modern browsers, you can use the map function to make it simpler :
function stringToIntArray(string) {
return string.split(',').map(function(v){ return parseInt(v, 10) });
}