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

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

Related

Why elements in array dont change after using callback function?

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)

How can I reverse the "includes()" method to "not-includes()" and retrieve the not included value?

Im trying to retrieve the not included value in the second array, by using the following code:
function diffArray(arr1, arr2) {
var newArr = [];
for (let i of arr1) {
if (arr2.includes(i)) {
newArr.push(i)
}
}
return newArr
}
console.log(
diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5])
)
Is there any way I can use another method to do this. I tried indexOf but I don't want the index.
Thank you
You can use filter():
let arr1 = [1, 2, 3, 5];
let arr2 = [1, 2, 3, 4, 5];
let result = arr2.filter(a2 => !arr1.includes(a2));
console.log(result);
if (!arr2.includes(i)) {
newArr.push(i)
}
! means not
You could always use else as well, but it's more lines of code:
if (arr2.includes(i)) {
// newArr.push(i)
} else {
newArr.push(i);
}
const a1 = [1, 2, 3, 4, 5];
const a2 = [1, 2, 3, 5];
function diffArray(arr1, arr2) {
const frequencies = arr1.concat(arr2).reduce((frequencies, number) => {
const frequency = frequencies[number];
frequencies[number] = frequency ? frequency + 1 : 1;
return frequencies;
}, {});
return Object.keys(frequencies).filter(number => frequencies[number] === 1);
}

Get Indexes of Filtered Array Items

In JavaScript, I have the following array
var arr = [5, 10, 2, 7];
From that array, I would like to get an array containing only the indexes of the items that are less than 10. So, in the above example, the indexes array would be
var indexes = [0, 2, 3];
Now, I want something simlar to filter, but that would return the indexes.
If I try filter, this is how it will work
var newArr = arr.filter(function (d) {
return (d < 10);
});
// newArr will be: [5, 2, 7];
This is not what I want. I want something along the following lines (note this is a pseudo-code)
var indexes = arr.filter(function (d) {
/* SOMETHING ALONG THE FOLLOWING PSEUDOCODE */
/* return Index of filter (d < 10); */
});
// indexes will be: [0, 2, 3];
How can I do that? Thanks.
Use a reducer.
var arr = [5, 10, 2, 7];
var newArr = arr.reduce(function(acc, curr, index) {
if (curr < 10) {
acc.push(index);
}
return acc;
}, []);
console.log(newArr);
You can use a forEach loop:
const arr = [5, 10, 2, 7];
const customFilter = (arr, min) => {
const result = [];
arr.forEach((element, index) => {
if (element < min) {
result.push(index);
}
});
return result;
}
console.log(customFilter(arr, 10));
You can use array#reduce and add indexes whose value is greater than 10.
var arr = [5, 10, 2, 7];
var indexes = arr.reduce((r, d, i) => d < 10 ? (r.push(i), r) : r , []);
console.log(indexes);

JavaScript: Convert [a,b,c] into [a][b][c]

I have arrays like [a], [a,b], [a,b,c] and so on.
How can I convert them into [a], [a][b], [a][b][c] and so on?
Example:
var arr = [1,2,3,4];
arr = do(arr); // arr = arr[1][2][3][4]
You could map it with Array#map.That returns an array with the processed values.
ES6
console.log([1, 2, 3, 4].map(a => [a]));
ES5
console.log([1, 2, 3, 4].map(function (a) {
return [a];
}));
While the question is a bit unclear, and I think the OP needs possibly a string in the wanted form, then this would do it.
console.log([1, 2, 3, 4].reduce(function (r, a) {
return r + '[' + a + ']';
}, 'arr'));
Functional:
use .map like this
[1,2,3,4].map(i => [i])
Iterative:
var list = [1, 2, 3, 4], result = [];
for (var i=0; i<list.length; i++) {
result.push([list[i]]);
}
If I understand you correctly, you are converting single dimension array to multi dimensional array.
To do so,
var inputArray = [1,2,3,4];
var outputArray = [];
for(var i=0;i<inputArray.length;i++)
{
outputArray.push([inputArray[i]])
}
function map(arr){
var aux = [];
for(var i=0; i<arr.length;++i){
var aux2 = [];
aux2.push(arr[i]);
aux.push(aux2);
}
return aux;
}

How can I reverse an array in JavaScript without using libraries?

I am saving some data in order using arrays, and I want to add a function that the user can reverse the list. I can't think of any possible method, so if anybody knows how, please help.
Javascript has a reverse() method that you can call in an array
var a = [3,5,7,8];
a.reverse(); // 8 7 5 3
Not sure if that's what you mean by 'libraries you can't use', I'm guessing something to do with practice. If that's the case, you can implement your own version of .reverse()
function reverseArr(input) {
var ret = new Array;
for(var i = input.length-1; i >= 0; i--) {
ret.push(input[i]);
}
return ret;
}
var a = [3,5,7,8]
var b = reverseArr(a);
Do note that the built-in .reverse() method operates on the original array, thus you don't need to reassign a.
Array.prototype.reverse() is all you need to do this work. See compatibility table.
var myArray = [20, 40, 80, 100];
var revMyArr = [].concat(myArray).reverse();
console.log(revMyArr);
// [100, 80, 40, 20]
Heres a functional way to do it.
const array = [1,2,3,4,5,6,"taco"];
function reverse(array){
return array.map((item,idx) => array[array.length-1-idx])
}
20 bytes
let reverse=a=>[...a].map(a.pop,a)
const original = [1, 2, 3, 4];
const reversed = [...original].reverse(); // 4 3 2 1
Concise and leaves the original unchanged.
reveresed = [...array].reverse()
The shortest reverse method I've seen is this one:
let reverse = a=>a.sort(a=>1)
**
Shortest reverse array method without using reverse method:
**
var a = [0, 1, 4, 1, 3, 9, 3, 7, 8544, 4, 2, 1, 2, 3];
a.map(a.pop,[...a]);
// returns [3, 2, 1, 2, 4, 8544, 7, 3, 9, 3, 1, 4, 1, 0]
a.pop method takes an last element off and puts upfront with spread operator ()
MDN links for reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop
two ways:
counter loop
function reverseArray(a) {
var rA = []
for (var i = a.length; i > 0; i--) {
rA.push(a[i - 1])
}
return rA;
}
Using .reverse()
function reverseArray(a) {
return a.reverse()
}
This is what you want:
array.reverse();
DEMO
Here is a version which does not require temp array.
function inplaceReverse(arr) {
var i = 0;
while (i < arr.length - 1) {
arr.splice(i, 0, arr.pop());
i++;
}
return arr;
}
// Useage:
var arr = [1, 2, 3];
console.log(inplaceReverse(arr)); // [3, 2, 1]
I've made some test of solutions that not only reverse array but also makes its copy. Here is test code. The reverse2 method is the fastest one in Chrome but in Firefox the reverse method is the fastest.
var array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var reverse1 = function() {
var reversed = array.slice().reverse();
};
var reverse2 = function() {
var reversed = [];
for (var i = array.length - 1; i >= 0; i--) {
reversed.push(array[i]);
}
};
var reverse3 = function() {
var reversed = [];
array.forEach(function(v) {
reversed.unshift(v);
});
};
console.time('reverse1');
for (var x = 0; x < 1000000; x++) {
reverse1();
}
console.timeEnd('reverse1'); // Around 184ms on my computer in Chrome
console.time('reverse2');
for (var x = 0; x < 1000000; x++) {
reverse2();
}
console.timeEnd('reverse2'); // Around 78ms on my computer in Chrome
console.time('reverse3');
for (var x = 0; x < 1000000; x++) {
reverse3();
}
console.timeEnd('reverse3'); // Around 1114ms on my computer in Chrome
53 bytes
function reverse(a){
for(i=0,j=a.length-1;i<j;)a[i]=a[j]+(a[j--]=a[i++],0)
}
Just for fun, here's an alternative implementation that is faster than the native .reverse method.
You can do
var yourArray = ["first", "second", "third", "...", "etc"]
var reverseArray = yourArray.slice().reverse()
console.log(reverseArray)
You will get
["etc", "...", "third", "second", "first"]
> var arr = [1,2,3,4,5,6];
> arr.reverse();
[6, 5, 4, 3, 2, 1]
array.reverse()
Above will reverse your array but modifying the original.
If you don't want to modify the original array then you can do this:
var arrayOne = [1,2,3,4,5];
var reverse = function(array){
var arrayOne = array
var array2 = [];
for (var i = arrayOne.length-1; i >= 0; i--){
array2.push(arrayOne[i])
}
return array2
}
reverse(arrayOne)
function reverseArray(arr) {
let reversed = [];
for (i = 0; i < arr.length; i++) {
reversed.push((arr[arr.length-1-i]))
}
return reversed;
}
Using .pop() method and while loop.
var original = [1,2,3,4];
var reverse = [];
while(original.length){
reverse.push(original.pop());
}
Output: [4,3,2,1]
I'm not sure what is meant by libraries, but here are the best ways I can think of:
// return a new array with .map()
const ReverseArray1 = (array) => {
let len = array.length - 1;
return array.map(() => array[len--]);
}
console.log(ReverseArray1([1,2,3,4,5])) //[5,4,3,2,1]
// initialize and return a new array
const ReverseArray2 = (array) => {
const newArray = [];
let len = array.length;
while (len--) {
newArray.push(array[len]);
}
return newArray;
}
console.log(ReverseArray2([1,2,3,4,5]))//[5,4,3,2,1]
// use swapping and return original array
const ReverseArray3 = (array) => {
let i = 0;
let j = array.length - 1;
while (i < j) {
const swap = array[i];
array[i++] = array[j];
array[j--] = swap;
}
return array;
}
console.log(ReverseArray3([1,2,3,4,5]))//[5,4,3,2,1]
// use .pop() and .length
const ReverseArray4 = (array) => {
const newArray = [];
while (array.length) {
newArray.push(array.pop());
}
return newArray;
}
console.log(ReverseArray4([1,2,3,4,5]))//[5,4,3,2,1]
As others mentioned, you can use .reverse() on the array object.
However if you care about preserving the original object, you may use reduce instead:
const original = ['a', 'b', 'c'];
const reversed = original.reduce( (a, b) => [b].concat(a) );
// ^
// |
// +-- prepend b to previous accumulation
// original: ['a', 'b', 'c'];
// reversed: ['c', 'b', 'a'];
Pure functions to reverse an array using functional programming:
var a = [3,5,7,8];
// ES2015
function immutableReverse(arr) {
return [ ...a ].reverse();
}
// ES5
function immutableReverse(arr) {
return a.concat().reverse()
}
It can also be achieved using map method.
[1, 2, 3].map((value, index, arr) => arr[arr.length - index - 1])); // [3, 2, 1]
Or using reduce (little longer approach)
[1, 2, 3].reduce((acc, curr, index, arr) => {
acc[arr.length - index - 1] = curr;
return acc;
}, []);
reverse in place with variable swapping (mutative)
const myArr = ["a", "b", "c", "d"];
for (let i = 0; i < (myArr.length - 1) / 2; i++) {
const lastIndex = myArr.length - 1 - i;
[myArr[i], myArr[lastIndex]] = [myArr[lastIndex], myArr[i]]
}
Reverse by using the sort method
This is a much more succinct method.
const resultN = document.querySelector('.resultN');
const resultL = document.querySelector('.resultL');
const dataNum = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const dataLetters = ['a', 'b', 'c', 'd', 'e'];
const revBySort = (array) => array.sort((a, b) => a < b);
resultN.innerHTML = revBySort(dataNum);
resultL.innerHTML = revBySort(dataLetters);
<div class="resultN"></div>
<div class="resultL"></div>
Using ES6 rest operator and arrow function.
const reverse = ([x, ...s]) => x ? [...reverse(s), x] : [];
reverse([1,2,3,4,5]) //[5, 4, 3, 2, 1]
Use swapping and return the original array.
const reverseString = (s) => {
let start = 0, end = s.length - 1;
while (start < end) {
[s[start], s[end]] = [s[end], s[start]]; // swap
start++, end--;
}
return s;
};
console.log(reverseString(["s", "t", "r", "e", "s", "s", "e", "d"]));
Infact the reverse() may not work in some cases, so you have to make an affectation first as the following
let a = [1, 2, 3, 4];
console.log(a); // [1,2,3,4]
a = a.reverse();
console.log(a); // [4,3,2,1]
or use concat
let a = [1, 2, 3, 4];
console.log(a, a.concat([]).reverse()); // [1,2,3,4], [4,3,2,1]
What about without using push() !
Solution using XOR !
var myARray = [1,2,3,4,5,6,7,8];
function rver(x){
var l = x.length;
for(var i=0; i<Math.floor(l/2); i++){
var a = x[i];
var b = x[l-1-i];
a = a^b;
b = b^a;
a = a^b;
x[i] = a;
x[l-1-i] = b;
}
return x;
}
console.log(rver(myARray));
JavaScript already has reverse() method on Array, so you don't need to do that much!
Imagine you have the array below:
var arr = [1, 2, 3, 4, 5];
Now simply just do this:
arr.reverse();
and you get this as the result:
[5, 4, 3, 2, 1];
But this basically change the original array, you can write a function and use it to return a new array instead, something like this:
function reverse(arr) {
var i = arr.length, reversed = [];
while(i) {
i--;
reversed.push(arr[i]);
}
return reversed;
}
Or simply chaning JavaScript built-in methods for Array like this:
function reverse(arr) {
return arr.slice().reverse();
}
and you can call it like this:
reverse(arr); //return [5, 4, 3, 2, 1];
Just as mentioned, the main difference is in the second way, you don't touch the original array...
How about this?:
function reverse(arr) {
function doReverse(a, left, right) {
if (left >= right) {
return a;
}
const temp = a[left];
a[left] = a[right];
a[right] = temp;
left++;
right--;
return doReverse(a, left, right);
}
return doReverse(arr, 0, arr.length - 1);
}
console.log(reverse([1,2,3,4]));
https://jsfiddle.net/ygpnt593/8/

Categories

Resources