I need your help since i'm stuck at the challenge from checkio.
What am i missing? I get back:
Your result:"one,two,three"
Right result:"one,three,two"
The Challenge:
You are given two string with words separated by commas. Try to find what is common between these strings. The words are not repeated in the same string.
Your function should find all of the words that appear in both strings. The result must be represented as a string of words separated by commas in alphabetic order.
UPDATE
this is my code:
function commonWords(first, second) {
const firstWord = first.split(',');
const secondWord = second.split(',');
let match = firstWord.filter(value => secondWord.includes(value));
return match.toString()
}
match.toString() doesn't change the value of match variable. You need to return it from the function.
function commonWords(first, second) {
const firstWord = first.split(',');
const secondWord = second.split(',');
let match = firstWord.filter(value => secondWord.includes(value));
return match.toString()
}
Explanation
There are two kinds of methods.
Mutator Methods
The first kind changes the original variable. You don't need to reassign the variable in case of those methods. Some of them are reverse(), fill(), etc
Note: These methods are only for reference type(objects, array) not for value types(string, number, boolean).
const arr = [1, 2, 3, 4];
arr.reverse();
console.log(arr); //[4, 3, 2, 1]
Accessor Methods
The second type are those methods which doesn't change the original variables but it returns are new value which is used by assigning it to a variable using =.
Some of them are map(), filter() etc.
let arr = [1, 2, 3, 4];
arr.map(x => x * x); //This line has no impact at all
console.log(arr) //Nothing is changed
arr = arr.map(x => x * x); //This line changes 'arr'
console.log(arr); //[1, 4, 9, 16]
Now toString() is of second type(accessor method) type. Just calling that method never changes the original variable. You need to reassign or return according to your needs
Related
I'm trying to write a function decreasingOrder which takes a positive integer as input and return an array of its digits in decreasing order.
e.g., decreasingOrder(1234) Should give [4,3,2,1].
function decreasingOrder(n) {
let unarr = [...`${n}`].map(i => parseInt(i)); //Unordered Array of Digits
let oarr = []; //Ordered Array of Digits
for(let j=0; j<unarr.length; j++){
let max = Math.max.apply(Math, unarr);
oarr.push(max);
unarr.splice(unarr.indexOf(max), 1); //delete element from array
}
return oarr;
}
console.log(decreasingOrder(1234));
//Expected [4,3,2,1], Instead got [4,3]
I think, deleting element using splice method also reduces the number
of iteration.
I also tried delete operator but get [4, NaN, NaN, NaN] (because Math.max([undefined])).
When I tried with specific number instead of unarr.length in condition expression for for loop, it works fine!
So when I use splice method to delete elements it reduces the unarr.length and when I tried to keep unarr.length constant using delete operator it gives NaN, what should I do? Is there any other way to write to the same function? I'm beginner in JavaScript.
The issue in your code is unarr.splice(unarr.indexOf(max), 1) inside loop.
By taking your example of console.log(decreasingOrder(1234)). In the first cycle the highest number from the array is found and is removed from the array and pushed to new array.
At the end of the first cycle the outputs will be unarr = [1, 2, 3], oarr = [4] and j=1
Likewise after second loop unarr = [1, 2], oarr = [4, 3] and j=2. Now the loop condition j < unarr.length is not satisfied hence the loop breaks. So the output will be [4, 3].
Instead you can use the below utility for your requirement.
function decreasingOrder(n) {
let unarr = [...`${n}`].map(i => parseInt(i)) //Unordered Array of Digits
return unarr.sort((a,b) => b-a)
}
console.log(decreasingOrder(1234))
Hope this helps.
Given two array of same length, return an array containing the mathematical difference of each element between two arrays.
Example:
a = [3, 4, 7]
b = [3, 9, 10 ]
results: c = [(3-3), (9-4), (10,7)] so that c = [0, 5 3]
let difference = []
function calculateDifferenceArray(data_one, data_two){
let i = 0
for (i in data_duplicates) {
difference.push(data_two[i]-data_one[i])
}
console.log(difference)
return difference
}
calculateDifferenceArray((b, a))
It does work.
I am wondering if there is a more elegant way to achieve the same
Use map as following:
const a = [3, 4, 7]
const b = [3, 9, 10]
const c = b.map((e, i) => e - a[i])
// [0, 5, 3]
for-in isn't a good tool for looping through arrays (more in my answer here).
"More elegant" is subjective, but it can be more concise and, to my eyes, clear if you use map:
function calculateDifferenceArray(data_one, data_two){
return data_one.map((v1, index) => data_two[index] - v1)
}
calculateDifferenceArray(b, a) // < Note just one set of () here
Live Example:
const a = [3, 4, 7];
const b = [3, 9, 10 ];
function calculateDifferenceArray(data_one, data_two){
return data_one.map((v1, index) => v1 - data_two[index]);
}
console.log(calculateDifferenceArray(b, a));
or if you prefer it slightly more verbose for debugging et. al.:
function calculateDifferenceArray(data_one, data_two){
return data_one.map((v1, index) => {
const v2 = data_two[index]
return v1 - v2
})
}
calculateDifferenceArray(b, a)
A couple of notes on the version of this in the question:
It seems to loop over something (data_duplicates?) unrelated to the two arrays passed into the method.
It pushes to an array declared outside the function. That means if you call the function twice, it'll push the second set of values into the array but leave the first set of values there. That declaration and initialization should be inside the function, not outside it.
You had two sets of () in the calculateDifferenceArray call. That meant you only passed one argument to the function, because the inner () wrapped an expression with the comma operator, which takes its second operand as its result.
You had the order of the subtraction operation backward.
You could use higher order array method map. It would work something like this:
let a = [2,3,4];
let b = [3,5,7];
let difference = a.map((n,i)=>n-b[i]);
console.log(difference);
you can read more about map here
I'm trying to delete max value from arMin and min value from arMax, but arr (is a const!) changes too! I don't know why. I am using Google Chrome version 65.0.3325.181.
'arr' is only one time declared and it shouldn't do nothing with that. I can't understand that. Tried with delete, but it's turning numbers into 'empty', but works the same and changes const too!
It's my first post, so if I do something wrong please forgive me.
const arr = [1, 2, 3, 4, 5];
let arMin = arr;
let arMax = arr;
let min = arMin.indexOf(Math.min.apply(null, arMin));
let max = arMax.indexOf(Math.max.apply(null, arMax));
arMin.splice(max, 1);
arMax.splice(min, 1);
console.log(arMin); // [2,3,4]
console.log(arMax); // [2,3,4]
console.log(arr); // [2,3,4]
The value of arr is a reference to an array.
You cannot change that. It will always be a reference to that array.
Arrays are mutable though, so you can change values in the array. const won't prevent that.
If you want arMin and arMax to be different arrays, then you need to make a copy of the array and not just copy the value of arr (which is a reference to that array).
const makes the reference constant, not the value.
You can't make arr point to something else, but you can change its values.
Note: other languages, Dart comes to mind, have the ability of specifying constant values. That's not the case of JavaScript.
When you make an array const then you can not change the reference
const arr = [1,2,3]
arr = [4,5,6] \\ Throws errors; You can not change const reference
arr[1] = 6; \\ Works fine. You are not changing the const reference. You are just mutating the array.
const x = 5; \\ Here constant is the value
x = x + 1; \\ Error. You can not change the constant value;
As a constant, you can't reassign its value, in this case, it contains the reference to the array.
But the array itself is not immutable.
An example would be:
const arr = [0,1,2,3,4,5];
arr = 'foo' // You cannot do that
arr.push(6) // That works fine. result: [0,1,2,3,4,5,6]
To complete previous answer, to make an exact copy of array instead of copying reference, you should do something like this :
const arr = [1, 2, 3, 4, 5];
let arMin = [...arr]; // We use spread operator to create new array from original one.
let arMax = [...arr];
let min = arMin.indexOf(Math.min.apply(null, arMin));
let max = arMax.indexOf(Math.max.apply(null, arMax));
arMin.splice(max, 1);
arMax.splice(min, 1);
console.log(arMin); // [1, 2, 3, 4]
console.log(arMax); // [2, 3, 4, 5]
console.log(arr); // [1, 2, 3, 4, 5]
--- EDIT 1 ---
i use TypeScript synthax to illustrate type
const arr = [1, 2, 3, 4, 5];
arr.push(6); // Is allow.
const object: {id: number, title: string} = {id: 1, title: 'Yanis'};
object.id = 2; // Is allow.
const myString: string = 'yanis';
myString = 'Jackob'; // Not allow.
I'm working on better understanding functional programming in javascript, but I'm a bit confused by what I've seen fed to map functions. Take the example below:
const f = x => (a, b, c) => b + a;
const arr = [1, 2, 3, 4, 5, 6];
const m = arr.map(f(1));
document.write(m);
When f returns a it will print each value, as expected. If it returns b it seems to return the index, and c will return the entire array for each value. Is there a reason to why this function works this way?
Array.prototype.map() callback function has three default parameters
The current element of the iteration
The index of the current element of the iteration
The array that .map() function was called upon
f returns a function which is set as callback of .map()
See also Array.from()
In your example, You are invoking map with a 3-ary callback where:
a -> current element
b -> current index
c -> original array
and returning c. Therefore, your result will be a new array containing a reference to the original array for every element iterated over.
Since you aren't doing anything with x, there is no need for a nested function here. A better example of how you can use this concept would be something like:
const add = a => b => a + b
const arr = [1, 2, 3, 4]
const newArr = arr.map(add(3))
// [4, 5, 6, 7]
console.log(newArr)
var NewdateData[] = [1,2,3,4,5,6,7,8,9,1,2,1,23,45,56]
This NewdateData is dynamically filled from database depending upon the selection made from the user interface.
I am using this NewdateData for displaying under the X axis Charts.
The issue I am facing is that, the values are not taken till the end , I want to have the last value to have under the X axis Labels.
xaxis: {tickFormatter: function(n)
{
var k = Math.round(n);
return NewdateData[k];
}
I am using flotr.
You can get the last value of an array with:
NewdateData[NewdateData.length-1];
Very late to the party, but for posterity: in ES2015/ES6 you can use Array.prototype.slice. Doesn't mutate the array and a negative number gives you elements from the end of the array as a new array.
So to get the last element:
let arr = [1, 2, 3, 4, 5];
let last = arr.slice(-1); // last = 5
I don’t have enough points to comment on Radman’s post., but his solution is wrong.
let arr = [1, 2, 3, 4, 5]; let last = arr.slice(-1); // last = 5
Returns [5], not 5.
The slice() method returns a shallow copy of a portion of an array
into a new array object selected from begin to end (end not included).
The original array will not be modified.
The correct answer:
let arr = [1, 2, 3, 4, 5];
let last = arr.slice(-1)[0];
References: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
Just do it with the map function.
this is the array what I want to pick the last item from it:-
const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];
loop over the array using map function to use the index parameter and compare it with animals array length:-
animals.map((animal, index) => animals.length -1 === index ? console.log("last item selected :)" + animal) : console.log("i'm not the last item"))
Now we are living with ES6 features
var arr = [1,2,3,4,5,6]
const [a, ...b] = arr.reverse();
console.log(a)
A simple and convenient way is to use Array.prototype.at()
function returnLast(arr) {
return arr.at(-1);
}
const cart = ['apple', 'banana', 'pear'];
const lastItem = returnLast(cart);
console.log(lastItem) //pear
or just
const lastItem = cart.at(-1)