How do I join these arrays is one? [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 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);
}

Related

Javascript: Why is my array.filter not registering values that were pushed?

I have an array, and I want to use .filter to count how many of each values there are in it, but my function seems to be ignoring any values that are pushed by another function.
My code looks a bit like this:
var arrToCheck = []
var ones = arrToCheck.filter(function(x) { return x == 1; })
var twos = arrToCheck.filter(function(x) { return x == 2; })
var threes = arrToCheck.filter(function(x) { return x == 3; })
function checkLength(input) {
length = input.length
switch (length) {
case 1:
arrToCheck.push(1)
break;
case 2:
arrToCheck.push(2)
break;
case 3:
arrToCheck.push(3)
break;
default:
console.log ("length too long")
}
}
So, for example, if the inputs are [A, I, TO, BUT, THE, SHE], then
arrToCheck should return [1, 1, 2, 3, 3, 3]
ones should return [1, 1].
But when I test it out, although arrToCheck returns including the pushed values as expected, the ones array will be empty.
The .filter function seems to be working though because when I enter values into the arrToCheck array in the source code, the .filter function registers those. It just ignores any 1s that are pushed by the checkLength switch.
I've also tried changing the 1s from string to number in various places, but it didn't seem to make a difference (as expected).
So it seems like the individual bits are working, but they don't work together? Am I missing something?
(also, bonus question, when an array.filter function returns error "TRUE isn't a function", what did I do wrong?)
The problem with your solution was that you not put strings length into arrToCheck array. Here is what you probably want to get (below code use arrow functions)
var input=["A", "I", "TO", "BUT", "THE", "SHE"]
var arrToCheck = input.map(x=>x.length);
var ones = arrToCheck.filter(x => x == 1)
var twos = arrToCheck.filter(x => x == 2)
var threes = arrToCheck.filter(x => x == 3)
// show results
j=JSON.stringify;
console.log('arrToCheck',j(arrToCheck));
console.log('ones',j(ones));
console.log('twos',j(twos));
console.log('threes',j(threes));
You need to update your arrays when a new input arrives, I have wrapped this update procedure on a function and called it after the a new input is pushed on arrToCheck. Also I have simplified the logic used by the switch ... case block.
var arrToCheck = [];
var ones = [], twos = [], threes = [];
function updateFilters()
{
ones = arrToCheck.filter(function(x) { return x == 1; });
twos = arrToCheck.filter(function(x) { return x == 2; });
threes = arrToCheck.filter(function(x) { return x == 3; });
}
function checkLength(input)
{
length = input.length;
if (length && length <= 3)
arrToCheck.push(length);
else
console.log ("length too long")
updateFilters();
}
// Main code:
checkLength("AA");
checkLength("AAA");
checkLength("AAAA");
checkLength("A");
console.log(
JSON.stringify(ones),
JSON.stringify(twos),
JSON.stringify(threes)
);
checkLength("AA");
checkLength("AAA")
console.log(
JSON.stringify(ones),
JSON.stringify(twos),
JSON.stringify(threes)
);
.filter isn't some magical thing that constantly runs on you array, it merely executes once on the array is it was when it executes. You'll need to run .filter every time you want to filter the content.
You just have to call these lines
var ones = arrToCheck.filter(function(x) { return x == 1; })
var twos = arrToCheck.filter(function(x) { return x == 2; })
var threes = arrToCheck.filter(function(x) { return x == 3; })
after you initialize the arrToCheck array.
var arrToCheck = []
function checkLength(input) {
length = input.length
switch (length) {
case 1:
arrToCheck.push(1)
break;
case 2:
arrToCheck.push(2)
break;
case 3:
arrToCheck.push(3)
break;
default:
console.log ("length too long")
}
}
['A', 'I', 'TO', 'BUT', 'THE', 'SHE'].forEach(x=>checkLength(x))
var ones = arrToCheck.filter(function(x) { return x == 1; })
var twos = arrToCheck.filter(function(x) { return x == 2; })
var threes = arrToCheck.filter(function(x) { return x == 3; })
console.log(ones)
In the checkLength() function as written, your input.length refers to the length of the array you are passing in -- rather than the lengths of the strings inside of the array.
Allow me to suggest a slightly modified version of checkLength:
function checkLength(input) {
console.log(`input is ${input}`);
console.log(`input.length is ${input}`);
length = input.length
switch (length) {
case 1:
arrToCheck.push(1)
break;
case 2:
arrToCheck.push(2)
break;
case 3:
arrToCheck.push(3)
break;
default:
console.log (`unexpected length: ${length}`)
}
}
If you do that and run
const input = ['A', 'I', 'TO', 'BUT', 'THE', 'SHE'];
checkLength(input);
You'll see the informative debugging information:
input is A,I,TO,BUT,THE,SHE
input.length is A,I,TO,BUT,THE,SHE
unexpected length: 6
Hope that helps get you unstuck.
When in doubt, add some console.logs() that can validate your understanding, or provide insight into where the code differs from your intentions.

How do I replace integers in an array with a string when it's a function parameter in JavaScript?

What I am trying to do is make a function that takes user input, splits that input into an array of numbers, then replaces each number with a string depending on what the number is. It seems all this does now is return undefined, because it doesn't want to reassign the index to what It tell it to. I want to do this using a for loop or the forEach method if possible.
Here is my code so far:
function stringify(num){
var array = num;
for (i in array) {
if (array[i] == 2) {
array[i] = "x";
} else if (array[i] == 5) {
array[i] = "y";
} else {
array[i] = "meow"
}
return array;
}
}
Here is an example of what I want to eventually happen:
stringify(52527);
y x y x meow
You could map the new array by using an object for the wanted replacings.
function stringify(num) {
return Array.from(num, v => ({ 2: 'x', 5: 'y' }[v] || v));
}
console.log(stringify('5252'));
With default value
function stringify(num) {
var values = { 2: 'x', 5: 'y', default: 'meow' };
return Array.from(num, v => values[v] || values.default);
}
console.log(stringify('52527'));
Convert the input data to a string, and split the string to characters:
function stringify(num) {
var array = String(num).split('');
for (i in array) {
if (array[i] === '2') {
array[i] = "x";
} else if (array[i] === '5') {
array[i] = "y";
} else {
array[i] = "meow"
}
}
return array; // the return should be after the loop ends
}
console.log(stringify(52527));
Another solution would be to use a Array.map() to iterate after the split, and an object with the characters that should be replaced:
function stringify(num) {
var rep = { 2: 'x', 5: 'y' };
return String(num)
.split('')
.map(function(c) {
return rep[c] || 'meow';
});
}
console.log(stringify(52527));
I think you might have a couple of problems:
Using a for ... in loop for an array or an iterator isn't ideal; rather use the construction for (var i = 0; i < array.length; i += 1).
As other commenters have said, make sure you're converting the passed argument, which is a Number, into a String. My preference for doing this something like var numString = '' + num;. If you're using es6, you could also use the template literal notation:
var numString = `${num}`;
Be careful of using the double equal sign == versus the triple equals === to check equality. The double equal will do some arcane type-casting of its operands. Safer to stick with the triple equal unless you're sure.
Strings are immutable, which means that while you can access the values of their indices, you can't change those values. I would suggest creating a new array that you then join upon return:
function stringify(num) {
var numString = '' + num;
var ret = [];
for (var i = 0; i < numString.length; i += 1) {
if (numString[i] === '2') { // The index values will be strings, not numbers now
ret.push('x');
} else if (numString[i] === '5') {
ret.push('y');
} else {
ret.push('meow');
}
}
return ret.join(' ');
}
this results in:
stringify(52527);
y x y x meow

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.

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

A function that will search an array for letters and return the position in which those letters are

I've created a function that will search for individual letters from a string regardless of case and order. Here is what it looks like.
function match(string, pattern) {
string = string.toLowerCase();
pattern = pattern.toLowerCase();
var patternarray = pattern.split("");
for (i = 0; i < pattern.length; i++) {
if (patternarray[i] >= "a" && patternarray[i] <= "z") {
if (string.indexOf(patternarray[i]) == -1) return false
}
}
return true
}
Now I want to do a similar thing except this time I will be searching an array, and instead of returning true/false I would like to return a new array containing the places in which the string pops up.
For example, if my variable contents were ["Oranges","Apples","Bananas"] and my search was "n", the function would return [0,2]. I am a beginner with JavaScript so thorough explanation would be helpful.
Thanks!
function matchArray(array, pattern) {
var i,
len = array.length,
result = [];
for (i = 0; i < len; ++i) {
if (match(array[i], pattern)) {
result.push(i);
}
}
return result;
}
Underscorejs has a function that should take care of this for you. Just take a look at the filter function. It has the ability to return a new array with items that passed a truth test.
var aArray = _.filter(['asdf','ddd','afsf'], function(item){
return (item.indexOf('a') !== -1);
}

Categories