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" ...
Related
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.
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
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,
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 8 years ago.
Improve this question
I have this simple problem, and I want a simple solution, if it exists.
Suppose I have the following string:
var myString = "IS is iS Is";
var myArray = [];
I want to get an array of size 4, where:
myArray[0] = 0;
myArray[1] = 3;
myArray[2] = 6;
myArray[3] = 9;
You can;
var myString = "IS is iS Is";
var myArray = [];
var re = /\b(is)\b/ig;
match = re.exec(myString);
while (match != null) {
myArray.push(match.index);
match = re.exec(myString);
}
document.write(myArray);
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 9 years ago.
Improve this question
I am creating one function in javaScript:
function myFunction() {
var str = "1,12,3,4";
if (str.contains("1,12,4,3")) {
alert("yes");
} else {
alert("No");
}
}
o/p: NO..i want the o/p as "Yes " because all elements are there.
I think you want to compare the comma separated elements contained in the string, not the string itself.
So you can use split and sort to build and sort your arrays and an "equality function" to check them.
Ref:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
You can try use a sorting/comaring function:
var str = "1,12,3,4";
var str2 = "1,12,4,3";
var myArray1 = str.split(",");
var myArray2 = str2.split(",");
alert(arraysEqual(myArray1, myArray2))
function arraysEqual(a, b) {
if (a === b) return true;
if (a == null || b == null) return false;
if (a.length != b.length) return false;
a.sort();
b.sort();
for (var i = 0; i < a.length; ++i) {
if (a[i] !== b[i]) return false;
}
return true;
}
Demo: http://jsfiddle.net/IrvinDominin/ZT4M8/
String "1,12,3,4" really doesn't contain substring "1,12,4,3". You're shuffling arrays and strings methods. You should convert your string to array (e.g. using split() method), then possible order and after all match.
try this
function myFunction() {
var str = "1,12,3,4";
var str_to_match = "1,12,4,3";
var res = str.split(",");
var res_to_match = str_to_match.split(",");
var flag=1;
for(var i=0; i<res_to_match.length; i++)
{
if(!res.contains(res_to_match[i]))
{
flag=0;
break;
}
}
if (flag==1) {
alert("yes");
} else {
alert("No");
}
}
I think, what you are looking for are the functions split, join and sort:
var myArray = str.split(","); // creates an array with your numbers
myArray.sort(); // sorts the array
var sortedStr = myArray.join(","); // creates a comma separated string of the sorted array