javascript - if else not resulting in expected comparision [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I am new to javascript. I am having a little issue here.
Is javascript if / else statement different than other languages (c++, java, python)?
Here is the issue that I am having.
if else statement only accepts i == 0 and i == 1 into my new array from myArray.
Why am I not be able to separate other elements into my new array? I used myArray for an example. In my real problem, I wouldn't know how many elements I have. That is why I have set up variables threetimes and increaseByThree. I am just trying to separate name, zip code, and amount into the different array by using a for loop.
var nameArray = [], zipCodeArray = [], totalAmountArray = [];
var threeTimes = 3;
var increaseByThree = 0;
var myArray = ["Eric ", "94990", "540", "Sam ", "303030", "350"];
for(var i = 0; i < myArray.length; i++) {
threeTimes += 3;
increaseByThree += 3;
if(i == threeTimes || i == 0) {
nameArray.push(myArray[i]);
} else if(i == increaseByThree || i == 1) {
zipCodeArray.push(myArray[i]);
} else {
totalAmountArray.push(myArray[i]);
}
}
console.log(nameArray)
console.log(zipCodeArray)
console.log(totalAmountArray)

Assuming your array will be in the format [a0, b0, c0, ....., aN, bN, cN] where N is the number of 'entries' - 1; you could simplify your logic that you determine where to put the value by:
const myArray = ["Eric ", "94990", "540", "Sam ", "303030", "350"];
const nameArray = [], zipCodeArray = [], totalAmountArray = [];
for(var i = 0; i < myArray.length; i++) {
switch (i % 3) {
case 0:
nameArray.push(myArray[i]);
break;
case 1:
zipCodeArray.push(myArray[i]);
break;
case 2:
totalAmountArray.push(myArray[i]);
break;
}
}
console.log(nameArray)
console.log(zipCodeArray)
console.log(totalAmountArray)
This will work for any size array and cuts out the need for the unnecessary variables and if-else blocks. Here is a helpful link for javascript's switch block
(https://www.w3schools.com/js/js_switch.asp) which are much cleaner as opposed to if-else blocks and show the intent more clearly in this case.

Related

insert a string at a specific position [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
i have an array and i want to insert "ZZ" if the current array value(string) contains "ata", the code should replace at the end of "ata" word.
var duplicatesArray = ["abıca","abrık","apşak","abbak","abu","aparma","apalisına","appak","aparmadutı","apşak","apışık","apşak","apışıklık","apışık","apalak","apılamak","apul","apul","apulamak","aparmak","at","arkasına","gelmek","ata","atabeg","at","eri","at","ağaç","at","oğlanı","at","akdarıcı","at","otayıcı","at","uşağı","at","oğlanı","at","oynağı","at","bırakmak","at","boynuna","düşmek","at","boynuna","düşmek","at","cıvlandurmak","at","çapmak","at","çapmak","at","depretmek","at","depmek","atı","doldurmak","at","segirtmek","ateş","evi","ateş","göyniigi","atışmak","ateşe","urmak","ateşe","nal","komak","at","şalmak","at","şalmak","at","tonı","at","kaşnısı","at","kaldırmak","at","kulağı","at","koparmals","at","koşmak","at","kulağı","götliği","atlaz","atlandurmak","atlandurmak","atlanmak","atlu","azuğı","atımı","yir","ata","atalar","atıcıduğı","aç","itmek","acıtğan","acıtmak","aç","dirilmek","acır","acırak","acışıklık","acışmak","aç","tutmak"
];
var uniqueArray = duplicatesArray.filter(function(elem, pos) {
return duplicatesArray.indexOf(elem) == pos;
});
for (var i = 0; i < uniqueArray.length; i++) {
var st = uniqueArray[i];
if((st.endsWith("mak")==false) && (st.endsWith("mek")== false) && (st.length>3))
{
var b = "ata";
var insert = "ZZ";
var position = st.indexOf("b");
st = st.slice(0, position) + insert + st.slice(position);
document.writeln(st);
document.write("<br>");
}
}
I may need to edit this answer later once some details have been clarified, but it seems like you should use the .map() method on your uniqueArray.
This code will walk through each word in the list and either let it unchanged or apply the replacement if all conditions are fulfilled.
// using a shorter, already deduplicated list for sake of clarity
var uniqueArray = [
"abıca","gelmek","ata","atabeg","at","eri","yir","atalar","tutmak"
];
var result = uniqueArray.map(function(word) {
return (
!word.endsWith("mak") &&
!word.endsWith("mek") &&
word.length > 3 ?
word.replace(/ata/, "ataZZ") : word
);
});
console.log(result);
I am right or wrong? :)
var initialArray = ["abıca","abrık","apşak","abbak","abu","aparma","apalisına","appak","aparmadutı","apşak","apışık","apşak","apışıklık","apışık","apalak","apılamak","apul","apul","apulamak","aparmak","at","arkasına","gelmek","ata","atabeg","at","eri","at","ağaç","at","oğlanı","at","akdarıcı","at","otayıcı","at","uşağı","at","oğlanı","at","oynağı","at","bırakmak","at","boynuna","düşmek","at","boynuna","düşmek","at","cıvlandurmak","at","çapmak","at","çapmak","at","depretmek","at","depmek","atı","doldurmak","at","segirtmek","ateş","evi","ateş","göyniigi","atışmak","ateşe","urmak","ateşe","nal","komak","at","şalmak","at","şalmak","at","tonı","at","kaşnısı","at","kaldırmak","at","kulağı","at","koparmals","at","koşmak","at","kulağı","götliği","atlaz","atlandurmak","atlandurmak","atlanmak","atlu","azuğı","atımı","yir","ata","atalar","atıcıduğı","aç","itmek","acıtğan","acıtmak","aç","dirilmek","acır","acırak","acışıklık","acışmak","aç","tutmak"];
var newArray = []
var regexp = /(ata)(.*)?/;
for (var i = 0; i< initialArray.length; i += 1) {
newArray.push(initialArray[i].replace(regexp, "$1ZZ$2"))
}
console.log(newArray)
// ... "gelmek", "ataZZ", "ataZZbeg" ...

Elegant method to compare an array of strings to another array of strings [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Question: How can I elegantly compare an array of strings to another array of strings thus returning an array of non-matching strings
var master = ['1','2','3','4']
var versioned = ['1a','2','3b','4']
var errorLog = []
var count = 0;
//this for loop doesn't work :(
for(var i = 0; i < versioned.length - 1; ++i ){
for(var j = 0; j < master.length -1; ++j){
if(versioned[i] === master[j]){
console.log('cleared');
}
if(count === master.length){
errorLog.push(versioned[i]);
}
}
}
loop will return ['1a', '3b'];
I feel like filter() or map() or reduce() will do this but I'm unable to wrap my brain around this properly.
var master = ['1','2','3','4'];
var versioned = ['1a','2','3b','4'];
function diff(needle, haystack){
return needle.filter(function(item){
return !~haystack.indexOf(item);
});
}
console.log(diff(versioned, master)); //["1a", "3b"];
~ NOTing any number equals -(x + 1). so ~-1 becomes 0, which is the only falsy.
~master.indexOf(item) is the same as master.indexOf(item) !== -1

how to create a json object in javascript for loop [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I would like to create a JSON object inside a for loop using javascript. I am expecting an result something like this:
{
"array":[
{
"value1":"value",
"value2":"value"
},
{
"value1":"value",
"value2":"value"
}
]
}
Can somebody help me on how to achieve this result in javascript ?
Instead of creating the JSON in the for-loop, create a regular JavaScript object using your for-loops and use JSON.stringify(myObject) to create the JSON.
var myObject = {};
for(...) {
myObject.property = 'newValue';
myObject.anotherProp = [];
for(...) {
myObject.anotherProp.push('somethingElse');
}
}
var json = JSON.stringify(myObject);
var loop = [];
for(var x = 0; x < 10; x++){
loop.push({value1: "value_a_" + x , value2: "value_b_" + x});
}
JSON.stringify({array: loop});
This code produces what you need:
var result = {"array": []};
for(var i = 0; i < 2; i++){
var valueDict = {};
for(var j = 0; j < 2; j++){
valueDict["value" + (j+1).toString()] = "value";
}
result["array"].push(valueDict);
}
It uses the push function to add items to the list, and the indexer [] notation notation to modify the entries on the object prototype.
Hope it helps,

Improving performance while iterating two nested loops [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
I calculate a "Top-5-List" of Birthplaces organized in an array of objects in this form
var myObjArr =[
{
"birth":
{
"year": 2012,
"name": "Manchester, Vermont, USA",
}
} , (and so on)
];
My approach however does not seem to be much performant:
for (var i = 0; i < myObjArr.length; i++) {
var alreadyListed = -1;
for (var j = 0; j < resultData.length; j++) {
if(resultData[j].key == myObjArr[i]['birth']['name']) { // birthname already in resultData
alreadyListed = j;
break;
}
}
if(alreadyListed != -1 ) { // birthname already in resultData -> raise count
resultData[alreadyListed].count += 1;
}else { // birthname not yet in resultData -> add to resultData
resultData.push({key: myObjArr[i]['birth']['name'], count: 1 });
}
}
}
Neiter javascript's forEach nor angulars angular.forEach seem to improve the performance. Any Suggestions?
You can use an object as a dictionary instead of using an array and looking for a key by iterating, this way the second "loop" is done by the Javascript implementation when looking for object keys (also it's probably not a linear scan but an hash table lookup):
var result = {};
myObjArr.forEach(function(obj) {
var key = "!" + obj.birth.name;
result[key] = 1 + (result[key] || 0);
});
I'm always adding a "!" in front of the key when using objects as dictionaries because all Javascript objects do have an inherited constructor property and I don't want to interfer with that.
The (x || 0) trick is to start with a 0 when a name has not seen before (undefined is falsy in Javascript). Adding 1 to undefined instead results in NaN.
If you really need an array as result the code is only slightly more complex:
var result = [];
var index = {};
myObjArr.forEach(function(obj) {
var key = "!" + obj.birth.name;
var ix = index[key];
if (ix === undefined) {
// Allocate a new entry
index[key] = result.length;
result.push({key:key, count:1});
} else {
result[ix].count += 1;
}
});

Using a Javascript switch statement, how can I count the number of elements (numbers only) in an array? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to count the number of elements (numbers only) in an array using a switch statement in the function. I honestly don't know exactly what this code would look like. But this is what I have so far
<script language="JavaScript">
//an array of numbers
var number = [1,"o",2,3,"a",0];
//a switch statement
switch (number) {
//Not sure what would go here....
break;
}
//display result of count
alert(count)
</SCRIPT>
using a switch statement
if you insist:
var count = 0;
for( var i=0 ; i<number.length ; ++i )
switch( typeof(number[i]) ) {
case "number": ++count; break;
}
count has value 4.
Note: NaN, Number.NEGATIVE_INFINITY, and Number.POSITIVE_INFINITY are also "number"s, so if you don't want to count these then do
var count = 0;
for( var i=0 ; i<number.length ; ++i )
switch( typeof number[i] ) {
case "number":
if( !isNaN(number[i]) && isFinite(number[i]) )
++count;
}
I think the current answers are not very compact.
Here is my take, using .reduce:
var number = [1,"o",2,3,"a",0];
var count = number.reduce(function(accum,cur){
return accum+(typeof cur === "number");
});
Here is a take using the required switch
var number = [1,"o",2,3,"a",0];
var count = number.reduce(function(accum,cur){
return accum+(typeof cur === "number");
switch(true){} // this switch's name is Alfred, after Batman's butler
});
var a = [1,"o",2,3,"a",0];
var nums = 0;
for(var i = 0;i<a.length;i++){
if(typeof a[i] == "number") nums++;
}
alert(nums);
Edit: Okay! A switch! Let's do it!
var count = 0;
for(var i = number.length; i--;){
switch(true){
case typeof number[i] == 'number':
count++;
}
}
alert(count);

Categories