This question already has answers here:
Simplest code for array intersection in javascript
(40 answers)
Compute intersection of two arrays in JavaScript [duplicate]
(4 answers)
Finding matches between multiple JavaScript Arrays
(13 answers)
Closed 5 years ago.
Let's take two arrays for example:
a = [1, 2, 3, 4, 5]
b = [4, 5, 6, 7, 8]
Now there is duplicates as we see 4 and 5. How to make new array from them instead of getting rid of them. What is the easiest solution?
So new array should be like:
newArray = [4, 5]
Thank you guys in advance!
You can do it using Array.filter() and Array.includes()
let a = [1, 2, 3, 4, 5];
let b = [4, 5, 6, 7, 8];
let arr = a.filter(function(x){
return b.includes(x);
})
console.log(arr);
Related
This question already has an answer here:
Get all elements in an array after a certain index in JavaScript
(1 answer)
Closed last month.
For example I have an array like [1, 2, 3, 4, 5] , and I want to select [3, 4, 5].
Is there a simple way to do that? Lots of thanks.
You can use slicing for this.
Lets say x = [1,2,3,4,5]. Just do s.slice(2).
You can just use a simple for loop and begin looping at the nth element of the array.
let array = [1, 2, 3, 4, 5]
for (let i = 2; i < array.length; i++) {
console.log(array[i])
}
This question already has answers here:
Convert array to JSON
(12 answers)
Closed 6 months ago.
This post was edited and submitted for review 5 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Array:
myArr = [[1, 2, 3], [4, 5, 6]]
Expected output:
newArr = "[[1, 2, 3], [4, 5, 6]]"
I have tried:
myArr.toString()
String(myArr)
myArr = `${myArr}`
What I got by doing the above methods:
'1,2,3,4,5,6'
I gather what you would like to achieve is more or less serialization. We could use JSON.stringify in JavaScript to serialize an Array.
const array = [[1, 2, 3], [4, 5, 6]];
const serializedArray = JSON.stringify(arr));
To deserialize the Array, JSON.parse could be used.
const originalArray = JSON.parse(serializedArray));
JSON.strinify is what you need.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
const myArr = [[1, 2, 3], [4, 5, 6]];
const myArrString = JSON.stringify(myArr);
console.log(`Here is my string: ${myArrString}`);
use JSON.stringify(myArr);
you can find out more on below link
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
This question already has answers here:
Merge/flatten an array of arrays
(84 answers)
Closed 3 years ago.
I want to create a function that accepts an array of both arrays and literals (or maybe objects) and flattens it to a single dimensional array. For example a valid input would be [5, [2, 3], 7, [9, 0, 1]], and the output of that input should be [5, 2, 3, 7, 9, 0, 1].
This is the code I have so far. There is nothing wrong with it, I just want to make sure it's as efficient as possible (it also needs to be es5 compatible).
function flattenArray(list) {
var result = [];
for (var index = 0; index < list.length; index++) {
result.push(list[index] instanceof Array ? list[index] : [list[index]]);
}
return [].concat.apply([], result);
}
console.log(flattenArray([5, [2, 3], 7, [9, 0, 1]]));
How about simply using Array.flat
function flattenArray(list) {
return list.flat()
}
console.log(flattenArray([5, [2, 3], 7, [9, 0, 1]]));
This seems to be second fastest ( based on the test link attached below ) and ES5 compatible
console.log([].concat.apply([],[5, [2, 3], 7, [9, 0, 1]]))
Performace test
Cocerning your code: There is no sense in wrapping single elements into arrays, .concat will handle them correctly, in other words:
[1].concat([2], 2)
just works, there is no need for wrapping 2 into [2]. That turns your code into a oneliner.
This question already has answers here:
How to create windowed slice of array in JavaScript?
(3 answers)
Closed 3 years ago.
I want solve a function called aperture which accept a number and an array that should return new array that should be composed of subarrays the size of the number with consecutive elements, for example aperture:
(3, [1, 2, 3, 4, 5]); // [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
Create an empty array whose length is equal to the given number and use reduce() on it.
const aperture = (num,arr) => [...Array(num)].reduce((ac,_,i) => {
ac.push(arr.slice(i,num+i));
return ac;
},[])
console.log(aperture(3,[1,2,3,4,5]))
This question already has answers here:
How Es6 rest and spread is working
(1 answer)
Spread Syntax ES6
(8 answers)
Closed 5 years ago.
I have come accross this syntax in a tutorial. Some say its not ES6 syntax. it was in a reduce function.
I need a clear explanation. What is going on in these parentethes ?
{...curr, ...acc}
full code..
const endShape = _(raw)
.filter(({key}) =>!/garbage/.test(key))
.map(({key,value})=>({[key]:value}))
.reduce((acc,curr)=>({...curr, ...acc}));
console.log(endShape);
Spread Operator Shorthand
The spread operator, introduced in ES6, has several use cases that make JavaScript code more efficient and fun to use. It can be used to replace certain array functions. The spread operator is simply a series of three dots.
Longhand
const odd = [1, 3, 5];
const nums = [2 ,4 , 6].concat(odd);
// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = arr.slice();
Shorthand
// joining arrays
const odd = [1, 3, 5 ];
const nums = [2 ,4 , 6, ...odd];
console.log(nums); // [ 2, 4, 6, 1, 3, 5 ]
// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = [...arr];