How to sort variable data in JavaScript [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 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

Related

How do I join these arrays is one? [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 4 months ago.
Improve this question
calculaNumeroDaSenha(['0110100000', '1001011111','1110001010', '0111010101','0011100110', '1010011001', '1101100100', '1011010100', '1001100111', '1000011000']);
function calculaNumeroDaSenha(senha) {
for (let i = 0; i < senha.length; i++) {
var dividir = senha[i].split('');
function filtro1(modo1) {
return modo1 == "1"
}
function filtro2(modo2) {
return modo2 == "0"
}
etapaFinal(dividir.filter(filtro1), dividir.filter(filtro2));
function etapaFinal(x,y) {
var novaArray = [];
if (x.length > y.length || x.length == y.length) {
novaArray.push('1')}
else {
novaArray.push('0');
}
console.log(novaArray);
};
}
}
the code output looks like this:
['0']
['1']
['1']
['1']
['1']
['1']
['1']
['1']
['1']
['0']
But I want the output to come out in just an array, like this:
['0111111110']
I've already tried methods like the join() function, but it didn't work:
function etapaFinal(x,y) {
var novaArray = [];
if (x.length > y.length || x.length == y.length) {
novaArray.push('1')}
else {
novaArray.push('0');
}
for (let a = 0; a < novaArray.length; a++) {
console.log(novaArray[i].join());
}
};
Please, if you have any idea how to do this, no matter how, help me if possible.
So it seems like your fundamental misunderstanding is how .push works. Push, as the name implies, pushes a new value to the end of the array. Thus instead of pushing to an array, what you need to do is just build up a string and then push that string at the end.
Looks like your code will either return a 1 or a 0 depending on what filter. Thus your new code can look like so:
function calculaNumeroDaSenha(senha) {
let result = '';
for (let i = 0; i < senha.length; i++) {
var dividir = senha[i].split('');
const filtro1 = (modo1) => {
return modo1 == "1"
}
const filtro2 = (modo2) => {
return modo2 == "0"
}
const etapaFinal = (x,y) => {
if (x.length > y.length || x.length == y.length) {
return '1';
}
else {
return '0';
}
};
result += etapaFinal(dividir.filter(filtro1), dividir.filter(filtro2));
}
return [result];
}
Where if we then log it out as so: console.log(calculaNumeroDaSenha(['0110100000', '1001011111','1110001010', '0111010101','0011100110', '1010011001', '1101100100', '1011010100', '1001100111', '1000011000']));
we get an array of size 1 of the following results: ['0111111110']. JSFiddle: https://jsfiddle.net/avnkj81z/
One thing I did, is I changed your inner function blocks to be defined instead using the following pattern: const <functionName> = <(parameters)> => {...}. This is because it makes it easier to read and you don't have one function nested in one after the other. Note that function A(b) { returns b; } is equivalent to const A = (b) => { returns b;}
To join all the strings into one string, use Array.join().
The question is kinda vague, you need to clarify what you're looking for:
if you are looking to group an array items into one string, you would use Array.join().
const arr = ['0110100000', '1001011111','1110001010', '0111010101','0011100110', '1010011001', '1101100100', '1011010100', '1001100111', '1000011000']
arr.join('');
// the above command would result in a single string with all array values concatenated
// "0110100000100101111111100010100111010101001110011010100110011101100100101101010010011001111000011000"
However if you're looking to group all array elements into one array that has a single string with all array elements grouped, you would use Array.join() followed by String.split()
const arr = ['0110100000', '1001011111','1110001010', '0111010101','0011100110', '1010011001', '1101100100', '1011010100', '1001100111', '1000011000']
arr.join('').split();
// the above command would result in a single array with one string with all array elements grouped
// [ "0110100000100101111111100010100111010101001110011010100110011101100100101101010010011001111000011000" ]
I think you want the output of this code. Please look into it. It is printing your desired value.
calculaNumeroDaSenha(['0110100000', '1001011111', '1110001010', '0111010101', '0011100110', '1010011001', '1101100100', '1011010100', '1001100111', '1000011000']);
function calculaNumeroDaSenha(senha) {
var novaArray = [];
var str = '';
for (let i = 0; i < senha.length; i++) {
var dividir = senha[i].split('');
function filtro1(modo1) {
return modo1 == "1"
}
function filtro2(modo2) {
return modo2 == "0"
}
etapaFinal(dividir.filter(filtro1), dividir.filter(filtro2));
function etapaFinal(x, y) {
if (x.length > y.length || x.length == y.length) {
str += 1;
}
else {
str += 0;
}
};
}
novaArray.push(str);
console.log(novaArray);
}

Check if string contains any of array of strings without regExp [duplicate]

This question already has answers here:
How to do case insensitive string comparison?
(23 answers)
How to check if a string contains text from an array of substrings in JavaScript?
(24 answers)
Closed 5 years ago.
I am checking a string input whether it contains any of an array of strings or not. It is passing most of the tests but not the below one.
Can anyone break my code down why it is not working properly?
function checkInput(input, words) {
var arr = input.toLowerCase().split(" ");
var i, j;
var matches = 0;
for(i = 0; i < arr.length; i++) {
for(j = 0; j < words.length; j++) {
if(arr[i] == words[j]) {
matches++;
}
}
}
if(matches > 0) {
return true;
} else {
return false;
}
};
checkInput("Visiting new places is fun.", ["aces"]); // returns false // code is passing from this test
checkInput('"Definitely," he said in a matter-of-fact tone.',
["matter", "definitely"])); // returns false; should be returning true;
Thank you for your time!
You can use functional methods for this. Try Array.some.
const words = ['matters', 'definitely'];
const input = '"Definitely," he said in a matter-of-fact tone.';
console.log(words.some(word => input.includes(word)));
You can use array#includes to check if a word exist in your input and convert both your input and words in lower case and then use array#includes.
function checkInput(input, words) {
return words.some(word => input.toLowerCase().includes(word.toLowerCase()));
}
console.log(checkInput('"Definitely," he said in a matter-of-fact tone.',
["matter", "definitely"]));
You can create regular expression and use i flag to specify case-insensitivity
function checkInput(input, words) {
return words.some(word => new RegExp(word, "i").test(input));
}
console.log(checkInput('"Definitely," he said in a matter-of-fact tone.',
["matter", "definitely"]));

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" ...

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;
}
});

Comparison an array in java script [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 8 years ago.
Improve this question
i have problem regarding how to compare string in an array..
in my list have jack,john,nami#domain,nami
function **alreadyInList**(list, toBeAdded) {
// return true or false
var delims = "(,)";
var tokens = list.split(delims);
for ( var i = 0; i < tokens.length; i++){
if (tokens[i] === toBeAdded ){
return true;
}
else
return false;
}
}
function addListTo(selectbox, textbox) {
var values = new Array();
var c = 0;
for ( i = 0; i < selectbox.options.length; i++) {
if (selectbox.options[i].selected) {
if (!**alreadyInList**(textbox.value,selectbox.options[i].value)) {
values[c++] = selectbox.options[i].value;
}
}
}
if (values.length == 0) return;
var v = values[0];
for (i = 1; i < values.length; i++) {
v += ',' + values[i];
}
if (textbox.value.length>0) {
if (textbox.value=='Any') {
textbox.value = v;
} else {
textbox.value += ',';
textbox.value += v;
}
} else {
textbox.value += v;
}
}
when i put my condition and i want to add the string into textbox it only work for the first string lets say i put nami as my string then when i want to put nami again it cannot so it works..but after "," i put name#domain .i can put back nami..means i dont want to repetitive string inside my textbox.can someone help me.sorry im still new in this programming..sorry for my english
Here is a revised version of your function to check if a name appears twice in any string in the array
function alreadyInList(list, toBeAdded) {
// return true or false
var delims = ",",
tokens = list.split(delims),
found = false;
var end = tokens.forEach(function (value) {
if (value.indexOf(toBeAdded) !== -1 && found == false) {
found = true;
alert('It\'s been found!');
// Do something
return true;
}
return false;
});
if (found != true) {
alert('Not in the list');
return false;
} else {
return false;
}
}
alreadyInList('marry,joe,gerry', 'marry');
JSFiddle Demo
Additionally if its just one occurance in the list you need something simple without a function.
var str = "marry,joe,gerry",
key = "marry";
if ( str.indexOf(key) !== -1 ) {
// Its found! Do something
}
As Sasquatch pointed out above, the issue is the delimiter you are using for split. You want to split by a single comma ',' -- not by the three characters '(,)'.
The way your code is written, tokens only ever has a single value because the split delimiter is wrong. It is matching the entire string variable list to your toBeAdded string and returning false.

Categories