Why elements in array dont change after using callback function? - javascript

I have some problems with understanding how callback function should work. I wanted to do a function that works just like map method. Even though I don't recive any errors, elements in array don't change. Could you point what am I doing wrong?
function multiplyFn(x) {
return x * 2;
}
const exampleArray = [1, 2, 3, 4, 5, 6, 8];
function mapFn(array, callback) {
for (const el of array) {
callback(el);
console.log(el)
}
console.log(array)
return array;
}
mapFn(exampleArray, multiplyFn);

if you want to change the original array you can update the index of the array arguments that you pass in function.
function mapFn(array, callback) {
array.forEach(function(element,index){
let val= callback(element)
array[index] = val
});
return array;
}

You need to update the elements by the returned values:
function multiplyFn(x) {
return x * 2;
}
let exampleArray = [1, 2, 3, 4, 5, 6, 8];
function mapFn(array, callback) {
for (let i = 0; i < array.length; i++) {
let el = array[i];
array[i] = callback(el);
}
return array;
}
mapFn(exampleArray, multiplyFn);

Note you can do this simply using Array#map() which will not update original but return a new array
function multiplyFn(x) {
return x * 2;
}
const exampleArray = [1, 2, 3, 4, 5, 6, 8];
function mapFn(array, callback) {
return array.map(callback);
}
console.log(mapFn(exampleArray, multiplyFn));

If you want to implement your own map function, you can do it without using any of the in-built array methods
//Define your map method in the Array prototype object
Array.prototype.mymap = function(callback) {
const res = [];
for (let index = 0; index < this.length; index++) {
res[index] = callback(this[index], index, this);
}
return res;
}
const exampleArray = [1, 2, 3, 4, 5, 6, 8];
//Let's test with two examples
function multiplyFn(x) {
return x * 2;
}
const first = exampleArray.mymap(multiplyFn)
console.log(first)
const second = exampleArray.mymap((el, index, array) => ({el, index}))
console.log(second)

Related

How do I use return in a function?

I have the following code:
const removeFromArray = function (xArray, xNumber) {
for(let i = 0; i < xArray.length; i++) {
if(xArray[i] === xNumber) {
const index = xArray.indexOf(xNumber);
const x = xArray.splice(index, 0);
} else {
console.log(xArray[i]);
}
}
};
removeFromArray([1, 11, 3, 4], 11);
The function takes 2 arguments, the array and the element that you want to delete from the array.
In order to check if the function is working, we have to use console.log. I used it and it's working. Now I have to implement this in an exercise and I need to remove the console.log and use return instead.
I tried using return but it only returns the first number in the array, like so:
return xArray[i];
So how can I return the whole array?
removeFromArray([1, 2, 3, 4], 3); // should remove 3 and return [1,2,4]
Use return xArray to return the entire array. Do this in the if block when you remove the element.
You need to specify length 1 in the splice() call to remove the element.
const removeFromArray = function (xArray, xNumber) {
for(let i = 0; i < xArray.length; i++) {
if(xArray[i] === xNumber) {
const index = xArray.indexOf(xNumber);
xArray.splice(index, 1);
return xArray;
}
}
};
console.log(removeFromArray([1, 11, 3, 4], 11));
You should use parameter value 1 of splice method. then return the array.hope it will work ex:
const removeFromArray = function (xArray, xNumber) {
let filteredArray = [];
for(let i = 0; i < xArray.length; i++) {
if(xArray[i] === xNumber) {
const index = xArray.indexOf(xNumber);
const x = xArray.splice(index, 1);
return x;
} else {
console.log(xArray[i]);
}
}
};
removeFromArray([1, 11, 3, 4], 11);

How to find the largest group of numbers in an array and return them separately in javascript?

How can I make a function that returns only the numbers greater than the number that I entered?
My code here isn't working, and I don't know why.
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var num = Number(prompt('number'));
function findBiggestNumbers(num) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] > num) {
num = arr[i];
}
}
return num;
// }
console.log(findBiggestNumbers(num));
To work with arrays you could use the filter function, it returns a subset of the array with some condition. So, you can simpley do:
var num = 5; //using 5 as an example
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var b = a.filter(number => number > num);
You can put this into an function.
You need to create a new empty array and fill it with numbers that are bigger than input value.
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var num = Number(prompt('number'));
function FindBiggestNumbers(num) {
let biggerThanArray = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i] > num) {
biggerThanArray.push(arr[i]);
}
}
return biggerThanArray;
}
console.log(FindBiggestNumbers(num));
You can start to understand and do some fun things with functional JS.
Similar to the answer from Daladier Sampaio I've used filter to return an array where each element passes a condition (el > num) in the callback function. (filter, reduce, and map were introduced in ES5 and are very useful array methods and well worth learning how to use.)
In this example, I've passed in - and called - a whole function named greaterThan instead.
greaterThan
1) Accepts an argument - n, the number from the prompt in this case
2) Returns an array - the callback function that will operate on each array element. What's interesting about this function is that it carries a copy of num with it when it returns. A function like this that retains a copy of its outer lexical environment like that is called a closure. Understanding what they are and how they work is a useful JS skill, and one that is often picked up on in JS interviews.
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const num = Number(prompt('number'));
// accepts a number and returns a callback function
// that accepts an array element and
// tests it against the value of `n`
function greaterThan(n) {
return function (el) {
return el > n;
};
}
// calling greater than with our prompted number
// returns that new callback function that checks each
// array element
const out = arr.filter(greaterThan(num));
console.log(out);
Modern JS >= ES6 will allow you to condense the amount of code you have to write using arrow functions. The following one-line code will work in place of the function in the example:
const greaterThan = n => el => el > n;
You could use Array.prototype.filter():
function FindBiggestNumbers(num) {
return arr.filter(n => n > num);
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var number = Number(prompt("Enter a number"));
console.log(FindBiggestNumbers(number));
The alternative is using a nested if statement inside a for loop like so:
First make a new array:
function FindBiggestNumbers(num) {
var newArr = [];
}
Then loop through the original array:
function FindBiggestNumbers(num) {
var newArr = [];
for (var i = 0; i < arr.length; i++) {
}
}
And if you find an element of the array greater than the number, add it to the new array:
function FindBiggestNumbers(num) {
var newArr = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i] > num) {
newArr.push(arr[i]);
}
}
}
Finally, return the new array:
function FindBiggestNumbers(num) {
var newArr = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i] > num) {
newArr.push(arr[i]);
}
}
return newArr;
}
Demonstration:
function FindBiggestNumbers(num) {
var newArr = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i] > num) {
newArr.push(arr[i]);
}
}
return newArr;
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var number = Number(prompt("Enter a number"));
console.log(FindBiggestNumbers(number));

in Javascript, how to create the new array using another array

The output that I want to have is newArray = [4, 9, 16, 25]. But I don't get it. Where did I make errors? Please help me.
var array = [2, 3, 4, 5];
var result = [];
function multiply(a) {
return a * a;
}
function newArray (a) {
for (i=0; i<a.lenght; i++){
result.push(multiply(a.value));
}
}
var newArray = newArray(array);
var array = [2, 3, 4, 5];
function multiply(a) {
return a * a;
}
function newArray (a) {
return a.map(multiply)
}
var result = newArray(array);
console.log(result)
This is another way to do it
const array = [2,3,4,5];
function multipliedArray(arr) {
return arr.map(x => x * x);
}
console.log(multipliedArray(array));
Keeping your logic as it is.
You misspelled a.length.
And you missed the index with array a.
var array = [2, 3, 4, 5];
var result = [];
function multiply(a) {
return a * a;
}
function newArray (a) {
for (i=0; i<a.length; i++){ //spelling mistake
result.push(multiply(a[i])); // index should be used
}
return result;
}
console.log(newArray(array));
I found that if I use ES6, I can change the codes like the following.
const arrayPast = [2, 3, 4, 5];
const result = [];
const appendArray = arrayPast.map(x => x * x);
result.push(appendArray);
Another thought, using forEach
const oldArray = [3, 4, 5, 6];
const square = [];
const newArray = oldArray.forEach((x) => square.push(x * x));

Filtering arguments from Arrays

The following code should take a given array and filter out all arguments that follow. For example the below code should return: [1, 1].
function destroyer(arr) {
var args= [];
args.push(arguments[0]);
var realArgs = args[0];
var filteredArr=[];
function removeIt (val){
return val != ;
}
filteredArr= realArgs.filter(removeIt);
return filteredArr;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
I can't figure out the filter function. Do I need to use Boolean somehow?
If you want to access the arguments of the function you should use arguments not args. The filtering part is not straightforward because javascript still doesn't have a builtin function we can use, so we have to implement it by ourselves (that's the includes function).
function destroyer(arr) {
var arr = arguments[0];
var toFilter = [];
for (var i = 0; i < arguments.length; i++)
toFilter.push(arguments[i]);
function removeIt (arr, numsToFilter){
var array = arr.slice(); // make sure to copy the array in order not to modify the original
for (var i = 0; i < array.length; i++) {
if (includes(numsToFilter, array[i])) {
delete array[i];
}
}
return array;
}
function includes(arr, k) {
for(var i=0; i < arr.length; i++){
if( arr[i] === k){
return true;
}
}
return false;
}
return removeIt(arr, toFilter);
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
Running the code-example
You can call Array#slice on the arguments object to convert it to an array. We'll slice from the index 1 (skip the arr). Then you can Array#filter the arr array. On each iteration check if the item is in the toRemove array by using Array#indexOf. Items that are in toRemove will be filtered out. Note - Array#filter returns a new array.
function destroyer(arr) {
// convert all the arguments but arr into array
var toRemove = [].slice.call(arguments, 1);
// filter the original array
return arr.filter(function removeIt(val){
// keep all vals that are not in the toRemove array
return toRemove.indexOf(val) === -1;
});
}
var result = destroyer([1, 2, 3, 1, 2, 3], 2, 3);
console.log(result);

freecodecamp Challenges- Seek and Destroy

I am trying to solve this challenge Seek and Destroy. I can't figure out what is wrong. Any help ?
Seek and Destroy
You will be provided with an initial array (the first argument in the destroyer function), followed by one or more arguments. Remove all elements from the initial array that are of the same value as these arguments.
This is the initial code below:
function destroyer(arr) {
// Remove all the values
return arr;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
This is my Code below:
function destroyer(arr) {
var letsDestroyThis = [];
var i =1 ; while (i<arguments.length) {
letsDestroyThis.push(arguments[i]);
i++;
}
for(var j=0 ; j< arguments[0].length; j++) {
for (var k= 0; k< letsDestroyThis.length; k++) {
if(arguments[0][j] === letsDestroyThis[k]){
arguments[0].splice(j, 1);
}
}
}
return arguments[0];
}
destroyer([2, 3, 2, 3], 2, 3);
Thanks in Advance!
You can create an array of all values that are supposed to be removed. Then use Array.filter to filter out these values.
Note: Array.splice will change original array.
function destroyer() {
var arr = arguments[0];
var params = [];
// Create array of all elements to be removed
for (var k = 1; k < arguments.length; k++)
params.push(arguments[k]);
// return all not matching values
return arr.filter(function(item) {
return params.indexOf(item) < 0;
});
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
function destroyer(arr) {
/* Put all arguments in an array using spread operator and remove elements
starting from 1 using slice intead of splice so as not to mutate the initial array */
const args = [...arguments].slice(1);
/* Check whether arguments include elements from an array and return all that
do not include(false) */
return arr.filter(el => !args.includes(el));
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
This worked for me:
function destroyer(arr) {
// Remove all the values
var args = Array.from(arguments);
var filter = [];
for (i = 0; i < args[0].length; i++) {
for (j = 1; j < args.length; j++) {
if (args[0][i] === args[j]) {
delete args[0][i];
}
}
}
return args[0].filter(function(x) {
return Boolean(x);
});
}
console.log(
destroyer([1, 2, 3, 1, 2, 3], 2, 3)
);
//two ways of resolving the Seek and Destroy challenge on the FreeCodeCamp
//I was trying to simplify this code, please post your solutions, simplifying the code
//as much has its possible
function destroyer1 (arr){
//get array from arguments
var args = Array.prototype.slice.call(arguments);
args.splice(0,1);
for (var i = 0; i < arr.length; i++){
for(var j = 0; j < args.length; j++){
if(arr[i]===args[j]){
delete arr[i];
}
}
}
return arr.filter(function(value){
return Boolean(value);
});
}
//--------------------------------------
function destroyer(arr) {
// Remove all the values
//Get values from arguments of the function to an array, index 0(arr[0] will be "arr",
//rest of indexes will be rest of arguments.
var args = Array.from(arguments);
for (var i = 0 ; i < args[0].length; i++){
for (var j = 1; j < args.length; j++){
if(args[0][i] === args[j]){
delete args[0][i];
}
}
}
return args[0].filter(function(value){
return Boolean(value);
});
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
console.log(destroyer1([1,6,3,9,8,1,1], 3,1));
This is my Code:
function destroyer(arr) {
var argsBeRemove = [...arguments];
argsBeRemove.shift();
return arr.filter(val => {
return argsBeRemove.indexOf(val) == -1;
});
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
Here is my version of Seek and Destroy. I assume that there are no zero elements in input (that assumption allows to pass the challenge). But that way I can make found elements equal zero and then just filter them out. It is pretty straight forward and no index mess when deleting elements in for loops.
function destroyer(arr) {
// Remove all the values
var args = Array.prototype.slice.call(arguments);
var temp = [];
temp = arguments[0].slice();
for (j = 1; j < args.length; j++) {
for (i = 0; i < arguments[0].length; i++) {
if (arguments[0][i] == arguments[j]) {
temp[i] = 0;
}
}
}
function isZero(value) {
return value !== 0;
}
var filtered = temp.filter(isZero);
return filtered;
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
function destroyer(arr) {
var args = Array.prototype.slice.call(arguments, 1);
return arr.filter(destroyNum);
function destroyNum(element) {
return !args.includes(element);
}
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
Give this a shot, it is way less convoluted:
function destroyer(arr) {
// arr1 is equal to the array inside arr
var arr1 = arr.slice(arguments);
// arr2 becomes an array with the arguments 2 & 3
var arr2 = Array.prototype.slice.call(arguments, 1);
// this function compares the two and returns an array with elements not equal to the arguments
return arr1.concat(arr2).filter(function(item) {
return !arr1.includes(item) || !arr2.includes(item)
})
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
You will be provided with an initial array (the first argument in the destroyer function), followed by one or more arguments. Remove all elements from the initial array that are of the same value as these arguments.
The accepted solution returns a new array, instead of removing the elements from the existing array.
This can be achieved efficiently by iterating the array in reverse and removing any elements matching any of the filter arguments.
function destroy(original, ...matches) {
if('length' in original) {
let index = original.length
while(--index > -1) {
if(matches.includes(original[index])) {
original.splice(index, 1)
}
}
}
return original;
}
const original = [1, 2, 3, 1, 2, 3]
destroy(original, 2, 3)
console.log(original);
My answer is similar to previous one, but I didn't use indexOf. Instead of that I checked the values in cycle, but compiler gives me a warning to not to declare function in cycle.
function destroyer(arr) {
// Remove all the values
var temp = [];
for (var i = 1; i < arguments.length; i++) {
temp.push(arguments[i]);
arr = arguments[0].filter(function(value) {
return ( value !== temp[i - 1]) ;
});
}
return arr;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
We can get the arguments behind the array, which are the number required to be removed and store them to a list. Then, we can just use a filter to filter out the numbers that needed to be removed.
function destroyer(arr) {
let removeList=[...arguments].slice(1);
return arr.filter(e=>removeList.indexOf(e)===-1);
}
I know isn't the shortest way to do it, but i think is the more simple to understand in an intermediate level.
function destroyer(arr, ...elements) {
var i =0;
while(i<=arr.length){ //for each element into array
for(let j =0; j<elements.length; j++){ //foreach "elements"
if(arr[i]==elements[j]){ // Compare element arr==element
arr.splice(i,1); //If are equal delete from arr
i--; //Check again the same position
j=0;
break; //Stop for loop
}
}
i++;
}
return arr;
}
console.log(destroyer(["possum", "trollo", 12, "safari", "hotdog", 92, 65, "grandma", "bugati", "trojan", "yacht"], "yacht", "possum", "trollo", "safari", "hotdog", "grandma", "bugati", "trojan"));
console.log(destroyer([1, 2, 3, 5, 1, 2, 3], 2, 3));
function destroyer(arr) {
let newArray = Array.from(arguments).splice(1)
return arr.filter(item => !(newArray.includes(item)))
}

Categories

Resources