Replace multiple string items in the array - javascript

I have an array that shows this value "135_1,undefined,undefined"
I have to find the "undefined" in the above array and then replace it with "0_0".Undefined can occur multiple times in the array.
I used
var extra = myVariable.replace("undefined", "0_0");
alert(extra);
but then I have to use this three times so that every single time it can search one and replace it.
I have also used this::
for (var i = 0; i < myVariable.length; i++) {
alert(myVariable[i]);
myVariable[i] = myVariable[i].replace(/undefined/g, '0_0');
}
alert(myVariable);
but it did'nt solved my purpose.

String.prototype.replace is a method accessible to strings. undefined is not a string.
This might help you.
for (var i=0, len=arr.length; i<len; i++) {
if (arr[i] === undefined) {
arr[i] = "0_0";
}
}
alert(JSON.stringify(arr));
You could also use Array.prototype.map for this. Note, it only works in IE >= 9
arr = arr.map(function(elem) {
return elem === undefined ? "0_0" : elem;
});

Since the question is tagged with jquery you can use $.map():
var extra = $.map(myVariable, function(item) {
return item || '0_0';
}
This will return a new array whereby each item comprising (in your case) an empty string or undefined is replaced by '0_0'.

var arr = ['135_1',undefined,undefined];
while(arr.indexOf(undefined) != -1) {
pos=arr.indexOf(undefined);
arr[pos]='0_0';
}

Related

How to get length of string in javascript without using native length method

I am working on a practice problem:
Return the length of a string without using javascript's native string.length method.
The only ways I could think of would be substring or slice, but I'm stumped.
You can loop over the string, testing to see whether there is a non-undefined value at each index (as soon as you get an undefined value you've run past the end of the string):
function strLength(s) {
var length = 0;
while (s[length] !== undefined)
length++;
return length;
}
console.log(strLength("Hello")); // 5
console.log(strLength("")); // 0
(I'm assuming that if you're not allowed to use the native string .length property that you probably shouldn't use the array .length property either with str.split("").length...)
Given that this is a practice problem, I suspect the OP may not want ES6/ES2015, but, just in case that's an option, and/or for whoever else is looking at this, here's a concise modern approach:
const str = "Hello world!";
console.log([...str].reduce(a => a+1, 0));
(When I posted this, no other answer had proposed this solution. However, I had missed the fact that #MarkoGrešak had essentially proposed this exact solution in a comment to another question.)
You can use spread element, Array.prototype.keys() iterator, Array.prototype.pop()
var str = "abc";
var len = [...[0,...str].keys()].pop();
console.log(len, str.length);
The briefest have been able to achieve so far using Object.keys(), Array.prototype.pop() and checking for empty string. Approach could probably be improved further.
var len = str === "" ? 0 : +Object.keys(str).pop()+1;
#nnnnnnn utilizes the two methods at above far exceeding the initial attempt in brevity and addressing case of empty string.
var len = +Object.keys(str+' ').pop();
One way would be iterating through a split string like so:
var count = 0;
Array.from("string here".split("")).forEach(function(){count++});
Tip from Marko below in the comments to use the reduce function to shorten it to:
var count = Array.from("string here".split("")).reduce(function(count){return count+1}, 0);
You could use array.length so you answer the question not using the native string.length.
var Str = "Hello world!";
const CountAr = Str.split("").length;
console.log(CountAr);
/*12*/
function stringLength(str) {
var count = 0;
var index = 0;
while(string[index] !== undefined){
count += 1;
index += 1;
}
return count;
}
I think this will work. If you start with '', it won't go into the while loop, and you'll just return 0.
function getStringLength(string) {
var idx = 0;
while (string[idx] !== undefined) {
idx += 1;
}
return idx;
}
This will work.
function length(str) {
str = str.split('');
var length = 0;
str.forEach(function(element) {
length++;
});
return length;
}
length('hello'); // output 5
Yet another way to do it
function getStringLength(str){
var count = 0;
for(var letter in str){
count += 1;
}
return count;
}
console.log(getStringLength('Mississippi')) // 11
console.log(getStringLength('')) // 0
The for in loop is the way to go I think. You can use slice or substring but for in loops can count strings easily too.
function getStringLength(string) {
var length = 0;
for (var i in string){
length++;
}
return length;
}
This is the solution I came up with
I have used a while loop for getting the length of the input
Sharing Two approaches with a while loop
Approach no 1
function getLength(input) {
if(!input){
return 'please provide input'
}
let i = 0;
while (true) {
if (input[i]) {
i += 1
}else{
break
}
}
return i
}
console.log(getLength([1, 5, 3, 7, 8])) // 5
console.log(getLength("Hare Krishna")) // 12
Output
5 (for array)
12 (for string)
Approach no 2
function getLength(input){
let i = 0;
while(input[i] !== undefined){
i++;
}
return i
}
console.log(getLength([1,2,3,48,8,9])) // 6
Output
6 (for array)
function getStringLength(string) {
// Do NOT use any native 'length' methods.
// You might consider using 'substring' or 'slice' as alternatives.
let i = 0;
while (Number(string.slice(i, i+1)) !== 0) {
i++;
} return i;
}
var output = getStringLength('hello');
console.log(output); // --> 5

Compare JavaScript Object-Array Property with String

Hello I have a quick question regarding my javascript array:
var firstrecord = {
name: 'Luca',
age: '19'
};
var secondrecord = {
name: 'Hans',
age: '25'
}
var myArray = [];
myArray.push(firstrecord,secondrecord);
Alright, now I have a var SearchString = "Lu".
What I'd do:
for (var i = 0; i < myArray.length; i++) {
if (myArray[i].[name].IndexOf(SearchString, i)) != 1){
return myArray[i];
}
}
But this doesn't work. Is there any solution to this problem ?
Update: indexOf != IndexOf
Reminder to self.. first lookup the use of such functions before misusing them. :)
Two errors here:
if (myArray[i].[name].IndexOf(SearchString, i)) != 1){
First, it's .indexOf(), lower-case "i". Second, you need just one or the other of . and [ ]:
if (myArray[i].name.indexOf(SearchString, i)) != 1)
Now, I don't know what it is you're trying to do here, but passing i as the second parameter of .indexOf() doesn't make much sense to me, and neither does comparing the return value to 1. If what you want to do is see if the search text appears at the start of the name, you'd do this:
if (myArray[i].name.indexOf(SearchString) == 0)

Faster code for checking repeated values in a JS array

var valueArray = ['ABC','DEF','GHI','ABC','JKL','MNO','DEF'];
var flag =false;
for(var i=0; i<valueArray.length; i++)
{
for(var j=0; j<valueArray.length; j++)
{
if(valueArray[j] == valueArray[i] && j != i)
{
flag = true;
break;
}
}
}
if(flag)
alert('same values found');
I am trying to validate one array by checking for duplicate values, i used above code, i don't think its a better way. is there any ways with jquery for this or some good js codes for it.
Not sure about jquery, but performance will be better with just one for loop:
for(var i = 0; i < valueArray.length; i++)
{
if (valueArray.indexOf(valueArray[i], i+1) != -1) {
flag = true;
break;
}
}
jsPerf test: http://jsperf.com/check-for-double-occurences
If you want a fast, compatible, "works everywhere" function that just checks for duplicates and doesn't require any library, consider:
function hasDups(arr) {
// Firstly copy array so don't affect original, then sort
var t = arr.slice().sort();
// If adjacent members have the same value, return true
for (var i=1, iLen=t.length; i<iLen; i++) {
if (t[i] === t[i-1]) return true;
}
return false;
}
console.log(hasDups(['abc','dvf','abc'])); // true
However you might want something a little more functional, e.g. that you can provide a compare function to so that, say, 'abc' == 'ABC' or '5' == 5.
Or if you want to use new features and avoid the copy and sort, consider:
function hasDups2(arr) {
var obj = {};
return arr.some(function(v){
if (obj.hasOwnProperty(v)) return true;
obj[v] = '';
});
}
The same strategy can be applied to the first as well and avoid ES5's some.
Note that both the above are only really suitable for comparing primitive values, though the first is better for that. If you want a reliable function to look for duplicate objects, that requires a bit more work.
Use jquery.unique() and compare the array size. If the size of the resultant array is not the same then return false.
Doc for jquery.unique()

Change a particular object in an array

Starting with an array of objects:
var array=[
{name:"name1",value:"value1"},
{name:"nameToChange",value:"oldValue"},
{name:"name3",value:"value3"}
];
How do change the value of a given property of one of the objects when another given property in the object is set to a given value?
For instance, starting with my array shown above, I wish to change value to "newValue" when name is equal to "nameToChange".
var array=[
{name:"name1",value:"value1"},
{name:"nameToChange",value:"newValue"},
{name:"name3",value:"value3"}
];
PS. To create the initial array, I am using jQuery's serializeArray(), and I do not wish to change the value of <input name="nameToChange">. I suppose I can change its value, use serialArray(), and then change it back, but this sounds more complicated than necessary.
The easiest way is to iterate over this array:
var i = arr.length;
while (i--) {
if (arr[i].name === 'nameToChange') {
arr[i].value = 'newValue';
break;
}
}
You won't be able to do the same stuff with native 'indexOf', as objects are to be compared.
for (var i = 0; i < array.length; i++) {
if (array[i].name == 'nameToChange') {
array[i].value = 'value';
break;
}
}
fiddle Demo
You need to go through all the elements and search for the required one and then replace with the value.
for(var i = 0; i < array.length; i++){
if(array[i]["name"] == str) {
array[i]["value"] = newValue;
break;
}
}
It's 2013; skip all the messy for loops and use forEach. It's much simpler and semantically cleaner:
array.forEach(function (e) {
if (e.name == 'nameToChange')
e.value = 'newValue';
})
Since you are using jQuery, you could use this:
$.each(array, function () {
if(this.name == 'nameToChange') this.value = 'value';
});
Fiddle

getElementsByTagName returning strings

My ultimate goal here is to get a list of radiobuttons and check/uncheck them. Here is my code:
for (var radio in document.getElementsByTagName('input')) {
if(typeof (radio) != "string")
alert(radio);
}
The alert never gets called.
The call to document.getElementsByTagName returns a list of strings numbered from 0 to the length of the list, so all of their properties (type, id, etc) are undefined and I can't really do much with them.
Am I doing something wrong here? Why aren't objects being returned for these elements?
This is in firefox 4 and chrome, if that helps.
getElementsByTagName returns a NodeList object, which is Array-like in the sense that it prototypes arbitrary numeric indices onto it.
You should not use a for..in loop to enumerate through a NodeList.
Why?
Because for..in iterates through all of the properties of an object, which will cause extra unwanted properties that exist in NodeList as well as the arbitrary indices prototyped
onto it (which, by the way are properties too.)
Since you are iterating through the indices, you are guaranteed not to get any object other than a DOMElement object. Therefore, you do not need the typeof check.
So, I think you meant to do this:
var els = document.getElementsByTagName('input');
for(var i = 0, j = els.length; i < j; i++) {
alert(els[i]);
}
Or, you can also do this, but I don't recommend it:
var els = document.getElementsByTagName('input');
for(var index in els) {
if(els.hasOwnProperty(index) && typeof index === 'number') {
//we have an element
alert(els[index]);
}
}
Try using a normal for loop. for ( x in obj ) loops over the properties of the object, not the actual elements of the array.
var els = document.getElementsByTagName("input");
for ( var i=0; i<els.length; i++ ) {
var radio = els[i];
if ( typeof(radio) != "string" ) {
alert(radio);
}
}
Live Demo
As others have stated, getElementsByTagName returns a NodeList object and you need to iterate through it differently. Here are some ways to accomplish your ultimate goal of checking/unchecking the radios.
With jQuery
$.each($('input[type="radio"]'), function () {
if (true) // Your condition for checking true
$(this).attr('checked','checked');
else
$(this).removeAttr('checked');
});
Without jQuery
var inputs = document.getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++){
var input = inputs.item(i);
if(input.type == "radio")
if (true) // Your condition for checking true
input.checked = "checked";
else
input.removeAttribute("checked");
}
}

Categories

Resources