Why is it behaving this way? [duplicate] - javascript

This question already has answers here:
Why does map() return an array with undefined values?
(1 answer)
Why does having [].map with curly brackets change the way it works?
(4 answers)
Closed 4 years ago.
When is run this, its printing undefined. while doing the ret.push(func(arr[i])) it does have the context right ?
function print(arr,func){
var ret =[]
for(let i =0 ;i<arr.length;i++){
ret.push(func(arr[i]))
}
return ret;
}
var numbers = [1,2,3,4,5];
console.log(print(numbers,(x)=>{x+1}));
it prints [undefined,undefined,undefined,undefined,undefined].

You could take a return statement and get the new values.
function print(arr, func) {
var ret = [];
for (let i = 0; i < arr.length; i++) {
ret.push(func(arr[i]));
}
return ret;
}
var numbers = [1, 2, 3, 4, 5];
console.log(print(numbers, (x) => { return x + 1; }));
// ^^^^^^
// or take a simplified lambda with implicit return (kudos paul!)
console.log(print(numbers, x => x + 1));

Related

My function does not return the expected output and I can't figure out why; can somebody point out something I'm missing? [duplicate]

This question already has answers here:
Array.fill(Array) creates copies by references not by value [duplicate]
(3 answers)
Closed 3 years ago.
my function has to take 2 arrays and if one of the arrays is shorter than the other it needs to fill in the blanks with nulls.
so i could do this easier now that i think about it but i would really like to know what i have missed.
the specific part of my code is the nested forEach loops i cant understand that when i invoke my function like this
fillSquare([1,2,3],[1,2,3,4,5])
I get [[1,2,3,4,5],[1,2,3,4,5]] instead of [[1,2,3,null,null][1,2,3,4,5]]
const fillSquare = arr => {
const maxArrayLength = Math.max(
...arr.map(arr => {
return arr.length;
})
);
let arrayMatrix = new Array(arr.length).fill(
new Array(maxArrayLength).fill(null)
);
arr.forEach((arry, mainIndex) => {
arry.forEach((item, subIndex) => {
console.log(mainIndex, "<--main", "sub-->", subIndex, "=", item);
arrayMatrix[mainIndex][subIndex] = item;
});
});
console.log(arrayMatrix);
return arrayMatrix;
};
When debugging, it seems:
let arrayMatrix = new Array(arr.length).fill(
new Array(maxArrayLength).fill(null)
);
// arrayMatrix[1] == arrayMatrix[0] => true
is only creating 1 array instance. setting 1 value on one sets it on both.
heres how to fix your issue
let arrayMatrix = new Array(arr.length).fill(0).map( _ => new Array(maxArrayLength).fill(null));
this is my version - now immutable
function fillSquare(arr) {
let clone = [...arr]
let maxDepth = arr.reduce( (c, subarr) => c = Math.max(c, subarr.length), 0)
clone.forEach((subarr, index) => {
let len = clone[index].length;
clone[index].length = maxDepth;
clone[index].fill(null, len, maxDepth);
})
return clone;
}
the import notes are you can set the length and fill the gaps. Also check out reduce if you need.
const fillSquare = function(arr){
let minLengthArr = arr[0];
let maxLength = arr[1].length;
if(arr[1].length < arr[0].length){
minLengthArr= arr[1];
maxLength = arr[0].length;
}
let itemsToPush = maxLength - minLengthArr.length;
for(let i=0;i<itemsToPush;i++){
minLengthArr.push(null);
}
return arr;
}
var r = fillSquare([[1,2,3],[1,2,3,4,5]]);
console.log(r);

Comparing arguments with an arguments in JavaScript

Please help me with this code; I am trying to compare arguments with an array elements and return when it matches, I don't know what is wrong with this code, it returns 1 rather than an array , thanks.
const removeFromArray = function() {
var delArgs = [] ;
//convert the arguments to an array called 'args'.
var args = Array.from(arguments);
var Arr = args[0];
//using foreach() and forloop to compare arguments with Arr elements.
Arr.forEach(function(x){
for (var j=1 ; j < args.length ; j++){
if(x == args[j]){
delArgs = delArgs.push(x);
}
}
});
return delArgs;
}
removeFromArray([1,2,3,4,5,6] , 5);
1
delArgs = delArgs.push(x);
You're overwriting delArgs with the return value from push, which is the new length of the array.
Don't do that.
since the question is already answered, you could use this for shorter code
const removeFromArray = (array, ...args) => {
return args.filter( arg => array.includes(arg) )
}
console.log(removeFromArray([1, 2, 3, 4, 5, 6], 5,6));

Javascript How to check if json array object appears more than once [duplicate]

This question already has answers here:
Check if an array contains duplicate values [duplicate]
(17 answers)
Closed 6 years ago.
"Rows":[
[0:"2017-01-01", 1:"Ontdekkingstocht"],
[0:"2017-01-01", 1:"Ontdekkingstocht"],
[0:"2017-01-02", 1:"Ontdekkingstocht"]]
How do I check if 0:"2017-01-01" appears more than once, and if so, return true?
Here's a fast way:
var data = {
"Rows": [
["2017-01-01", "Ontdekkingstocht"],
["2017-01-01", "Ontdekkingstocht"],
["2017-01-02", "Ontdekkingstocht"]
]
};
function dupes(data) {
var cnt = {};
data.Rows.forEach((i) => { cnt[i[0]] = 1 });
return Object.keys(cnt).length < data.Rows.length;
}
console.log(dupes(data));
Here a fonction doing that, with your array as parameter:
function checkDuplicate(arr){
var i = 0;
while(i < arr.length-1){
arr.slice(i+1).forEach(function(element) {
if(element[0] == arr[i][0])return true;
});
}
return false;
}
A fast readable way is:
const rows = [
["2017-01-01", "Ontdekkingstocht"],
["2017-01-01", "Ontdekkingstocht"],
["2017-01-02", "Ontdekkingstocht"]
];
const duplicates = rows
.reduce((prev, curr) => [...prev, ...curr])
.some((element, index, array) => array.filter(el => element === el));
console.log(duplicates);

why is javascript treating variable as string? [duplicate]

This question already has answers here:
Why is using "for...in" for array iteration a bad idea?
(28 answers)
Closed 6 years ago.
In the following code why is i treated as a string? I have to multiple it by 1 to get it to convert back to a number.
getPositionInArray(value, array) {
console.log('array = ', array);
let i = 0; // why is i a string?
for (i in array) {
if (array[i].toLowerCase() === value) {
let positionOnUI = i * 1 + 1; // why can't I use i + 1?
return positionOnUI;
}
}
return null;
}
just use a normal for loop and you wont have this issue:
Working Example
function getPositionInArray (value, array) {
console.log('array = ', array);
for (let i = 0; i < array.length; i++) {
if (array[i].toLowerCase() === value) {
let positionOnUI = i // why can't I use i + 1?
return positionOnUI;
}
}
return null;
}
assuming the array is an array...
the problem is for(i in array) that treats the array as an object and return the indexes as strings:
change the loop in for(;i<array.length;i++) and it should work.

some elements are not removed from array [duplicate]

This question already has answers here:
Remove items from array with splice in for loop [duplicate]
(5 answers)
Closed 6 years ago.
i have created an array for vowels position in string now i want reomve all elements that have value -1 from this array but its not working
function translatePigLatin(str) {
var vowelp=[];
var newarr=str.split('');
vowelp.push(newarr.indexOf('a'));
vowelp.push(newarr.indexOf('e'));
vowelp.push(newarr.indexOf('i'));
vowelp.push(newarr.indexOf('o'));
vowelp.push(newarr.indexOf('u'));
var minvowel=vowelp[0];
for(var i=0;i<vowelp.length;i++) { //looping through vowel's position array
if(vowelp[i]==-1) {
vowelp.splice(i,1);
console.log(vowelp[i]);
}
}
return vowelp;
}
input-translatePigLatin("consonant");
output that i am getting is[6,-1,1] but i want [6,1]
Simple way is to use filter()
function translatePigLatin(str) {
var vowelp = [];
var newarr = str.split('');
vowelp.push(newarr.indexOf('a'));
vowelp.push(newarr.indexOf('e'));
vowelp.push(newarr.indexOf('i'));
vowelp.push(newarr.indexOf('o'));
vowelp.push(newarr.indexOf('u'));
var minvowel = vowelp[0];
return vowelp.filter(function(v) {
return v != -1;
})
}
console.log(translatePigLatin("consonant"));
In your case you need to decrement the value of i in case of item removal otherwise it will skip the next element.
function translatePigLatin(str) {
var vowelp = [];
var newarr = str.split('');
vowelp.push(newarr.indexOf('a'));
vowelp.push(newarr.indexOf('e'));
vowelp.push(newarr.indexOf('i'));
vowelp.push(newarr.indexOf('o'));
vowelp.push(newarr.indexOf('u'));
var minvowel = vowelp[0];
for (var i = 0; i < vowelp.length; i++) { //looping through vowel's position array
if (vowelp[i] == -1) {
vowelp.splice(i, 1);
i--;
console.log(vowelp[i]);
}
}
return vowelp;
}
console.log(translatePigLatin("consonant"));
You can make it more simple using map() and filter() with an array
function translatePigLatin(str) {
return ['a', 'e', 'i', 'o', 'u'].map(function(v) {
return str.indexOf(v);
}).filter(function(v) {
return v != -1;
});
}
console.log(translatePigLatin("consonant"));
you are calling splice on the same array you are iterating over. Rememeber splice is mutable and it deletes from the original array. As a result of that your index tracking logic is getting messed up. So instead you could use delete[i] (which does not mess up the indexes and creates a void)
function translatePigLatin(str) {
var vowelp=[];
var newarr=str.split('');
vowelp.push(newarr.indexOf('a'));
vowelp.push(newarr.indexOf('e'));
vowelp.push(newarr.indexOf('i'));
vowelp.push(newarr.indexOf('o'));
vowelp.push(newarr.indexOf('u'));
var minvowel=vowelp[0];
for(var i=0;i<vowelp.length;i++) { //looping through vowel's position array
if(vowelp[i]==-1) {
delete vowelp[i];
}
}
return vowelp;
}
console.log(translatePigLatin("consonant")); //prints [6, 3: 1]
which means you have 6 at index 0 and 1 at index 3
I would prefer a simpler code:
function translatePigLatin(str) {
var vowelp = [];
var vowels = ['a','e','i','o','u'];
for (var i = 0; i < vowels.length; i++) {
var index = str.indexOf(vowels[i]);
if (index != -1) {
vowelp.push(index);
}
}
return vowelp;
}

Categories