Related
So, I've the following arrays of odd numbers:
const oddNums = [1, 3, 5, 7, 9];
And I want to fill it with the missing even numbers to obtain the result below:
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
I've done it like this and it works fine, but can it be done in a more concise manner, maybe using array methods?
const oddNums = [1, 3, 5, 7, 9];
const nums = [];
for (let i=0; i<oddNums.length; i++) {
nums.push(oddNums[i]);
nums.push(oddNums[i] + 1);
}
console.log(nums);
Note: The odd numbers would always be in sequence but might not begin with 1, for ex: [11, 13, 15] is a valid array. And the output for [11, 13, 15] should be [ 11, 12, 13, 14, 15, 16 ].
The only information you need is the first (odd) number and the size of the input:
const oddNums = [1, 3, 5, 7, 9];
const result = Array.from({length: oddNums.length*2}, (_, i) => i + oddNums[0]);
console.log(result);
Using Array.prototype.flatMap:
const
oddNums = [1, 3, 5, 7, 9],
nums = oddNums.flatMap(n => [n, n + 1]);
console.log(nums);
Using Array.prototype.reduce and Array.prototype.concat:
const
oddNums = [1, 3, 5, 7, 9],
nums = oddNums.reduce((r, n) => r.concat(n, n + 1), []);
console.log(nums);
Using Array.prototype.reduce and Array.prototype.push:
const
oddNums = [1, 3, 5, 7, 9],
nums = oddNums.reduce((r, n) => (r.push(n, n + 1), r), []);
console.log(nums);
This question already has answers here:
Merge two arrays with alternating values
(14 answers)
Merge Two Arrays so that the Values Alternate
(6 answers)
interleave mutliple arrays in javascript
(2 answers)
Closed 1 year ago.
I have two arrays.
let a = [1, 3, 5, 7]
let b = [2, 4, 6, 8]
I want the result:
a = [1, 2, 3, 4, 5, 6, 7, 8]
How can I insert each of array B's elements every other element in array A?
I have tried using splice in a for loop, but the length of array A changes so I cannot get it to work.
You can create a new array, loop through a and push the current item and the item in b at the same index:
let a = [1, 3, 5, 7];
let b = [2, 4, 6, 8];
let res = []
a.forEach((e,i) => res.push(e, b[i]))
console.log(res)
Alternatively, you can use Array.map and Array.flat:
let a = [1, 3, 5, 7];
let b = [2, 4, 6, 8];
let res = a.map((e,i) => [e, b[i]]).flat()
console.log(res)
If the arrays have the same length, then you can use flat map to avoid mutating the original array.
const a = [1, 3, 5, 7];
const b = [2, 4, 6, 8];
const res = b.flatMap((elem, index) => [a[index], elem]);
console.log(res);
You can try:
let a = [1, 3, 5, 7];
let b = [2, 4, 6, 8]
let newArray = [...a, ...b]
console.log(newArray) // [1, 3, 5, 7, 2, 4, 6, 8]
If you want to sort just
let a = [1, 3, 5, 7];
let b = [2, 4, 6, 8]
let newArray = [...a, ...b].sort((a, b) => a - b)
console.log(newArray) // [1, 2, 3, 4, 5, 6, 7, 8]
Create a new array and flatten it by doing the below.
let a = [1, 3, 5, 7]
let b = [2, 4, 6, 8]
console.log(a.map((e, i)=> [e, b[i]]).flat());
You could transpose the data and get a flat array.
const
transpose = (a, b) => b.map((v, i) => [...(a[i] || []), v]),
a = [1, 3, 5, 7],
b = [2, 4, 6, 8],
result = [a, b]
.reduce(transpose, [])
.flat();
console.log(result);
Don't splice, just create a new array and push them in on every other index.
Do a for loop, and on each loop do
newArrary.push(a[i]);
newArrary.push(b[i]);
You can use reduce
let a = [1, 3, 5, 7];
let b = [2, 4, 6, 8];
let c = a.reduce((acc, x, i) => acc.concat([x, b[i]]), []);
console.log(c)
This works for arrays of any length, adapt the code based on the desired result for arrays that are not the same length.
Using forEach and pushing the current element and the relative element from the other array is an option
let a = [1, 3, 5, 7];
let b = [2, 4, 6, 8];
let c = [];
a.forEach((x, i) => {c.push(x, b[i])});
console.log(c);
More about forEach - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
Let say there are two array.
let MotherArray = [
[30, 1, 2, 3, 4, 5, 6],
[5, 6, 7, 8, 9],
[7, 8, 9],
];
let arraytoTest = [5,6];
What i want is that i want to return the array if
all the value inside the arraytoTest is included in the MotherArray[i]
I have tried
let MotherArray = [[30, 1, 2, 3, 4, 5, 6],[5, 6, 7, 8, 9],[7, 8, 9],];
let arraytoTest = [5, 6];
let result = MotherArray.includes(arraytoTest)
console.log(result);
But i don't think this is the correct method.
I also find the array.every() but i think my usage is not correct.
What I want is that I want to return MotherArray[0],MotherArray[1] which are [[30, 1, 2, 3, 4, 5, 6],[5, 6, 7, 8, 9]] in this particular example
since 5 and 6 are includes inside these 2 arrays.
You can combine array.filter() with array.every()
let MotherArray = [
[30, 1, 2, 3, 4, 5, 6],
[5, 6, 7, 8, 9],
[7, 8, 9],
];
let arraytoTest = [5,6];
let found = MotherArray.filter(childArray => arraytoTest.every(num => childArray.includes(num)));
console.log(found);
I think this is what you want; A combination of filter on the mother array and every for array you're testing.
let MotherArray = [
[30, 1, 2, 3, 4, 5, 6],
[5, 6, 7, 8, 9],
[7, 8, 9],
];
let arraytoTest = [5,6];
let result = MotherArray.filter(arr => arraytoTest.every(x => arr.indexOf(x)>-1));
console.log(result);
You can use filter and every like below.
Or you can use filter and some with negative condition like filter(x => !arraytoTest.some(y => !x.includes(y))). I think with some it would be efficient because
The some() method executes the callback function once for each element present in the array until it finds the one where callback returns a truthy value.
let MotherArray = [
[30, 1, 2, 3, 4, 5, 6],
[5, 6, 7, 8, 9],
[7, 8, 9],
];
let arraytoTest = [5,6];
let result = MotherArray.filter(x => arraytoTest.every(y => x.includes(y)));
console.log(result);
let result2 = MotherArray.filter(x => !arraytoTest.some(y => !x.includes(y)));
console.log(result2);
This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Closed 3 years ago.
I received this question for practice and the wording confused me, as I see 2 results that it might want.
And either way, I'd like to see both solutions.
For example, if I have an array:
let arr = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10];
I'm taking this as wanting the final result as either:
let finalResult = [1, 2, 3, 4, 5, 8, 9, 10];
OR:
let finalResult = [1, 9, 10];
The difference between the two being, one just removes any duplicate numbers and leaves the rest and the second just wants any number that isn't a duplicate.
Either way, I'd like to write two functions that does one of each.
This, given by someone else gives my second solution.
let elems = {},
arr2 = arr.filter(function (e) {
if (elems[e] === undefined) {
elems[e] = true;
return true;
}
return false;
});
console.log(arr2);
I'm not sure about a function for the first one (remove all duplicates).
Using Set and Array.from()
let arr = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10];
console.log(Array.from(new Set(arr)));
Alternate using regex
regex explanation here
let arr = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10];
let res = arr
.join(',')
.replace(/(\b,\w+\b)(?=.*\1)/ig, '')
.split(',')
.map(Number);
console.log(res);
Alternate using objects
let arr = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10];
let obj = arr.reduce((acc, val) => Object.assign(acc, {
[val]: val
}), {});
console.log(Object.values(obj));
Just use a simple array.filter one-liner:
let arr = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10];
let finalResult = arr.filter((e, i, a) => a.indexOf(e) == i).sort(function(a, b){return a - b});
console.log(finalResult);
You could use another filter statement if you wanted the second result:
let arr = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10];
let finalResult = arr.filter((e, i, a) => a.filter(f => f == e).length == 1).sort(function(a, b){return a - b});
console.log(finalResult);
For the first part you can use Set() and Spread Syntax to remove duplicates.
let arr = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10];
let res = [...new Set(arr)]
console.log(res)
For the second part you can use reduce()
let arr = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10];
//to get the object with count of each number in array.
let obj = arr.reduce((ac,a) => {
//check if number doesnot occur before then set its count to 1
if(!ac[a]) ac[a] = 1;
//if number is already in object increase its count
else ac[a]++;
return ac;
},{})
//Using reduce on all the keys of object means all numbers.
let res = Object.keys(obj).reduce((ac,a) => {
//check if count of current number 'a' is `1` in the above object then add it into array
if(obj[a] === 1) ac.push(+a)
return ac;
},[])
console.log(res)
You can use closure and Map
let arr = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10];
const build = ar => {
const mapObj = ar.reduce((acc, e) => {
acc.has(e) ? acc.set(e, true) : acc.set(e, false)
return acc
}, new Map())
return function(hasDup = true) {
if(hasDup) return [...mapObj.keys()]
else return [...mapObj].filter(([key, val]) => !val).map(([k, v])=> k)
}
}
const getArr = build(arr)
console.log(getArr())
console.log(getArr(false))
You can create both arrays in One Go
let arr = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10];
let unique = new Set();
let repeated = Array.from(arr.reduce((acc, curr) => {
acc.has(curr) ? unique.delete(curr) : acc.add(curr) && unique.add(curr);
return acc;
}, new Set()));
console.log(Array.from(unique))
console.log(repeated)
You can use Array.prototype.reduce() create a hash object where the keys are the numbers in the array and the values are going to be the the repeated occurrence of numbers in the arr array variable..
Then using Object.keys():
Remove all duplicates Object.keys(hash)
Remove all duplicates but filtering with Array.prototype.filter() to get the numbers with only one occurrence
Code:
const arr = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10];
const hash = arr.reduce((a, c) => (a[c] = (a[c] || 0) + 1, a), {});
// [1, 2, 3, 4, 5, 8, 9, 10];
const finalResultOne = Object.keys(hash);
// [1, 9, 10];
const finalResultTwo = Object.keys(hash).filter(k => hash[k] === 1);
console.log('finalResultOne:', ...finalResultOne);
console.log('finalResultTwo:', ...finalResultTwo);
You could sort the array before and filter the array by checking only one side for duplicates or both sides.
var array = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10],
result1,
result2;
array.sort((a, b) => a - b);
result1 = array.filter((v, i, a) => a[i - 1] !== v);
result2 = array.filter((v, i, a) => a[i - 1] !== v && a[i + 1] !== v);
console.log(...result1);
console.log(...result2)
As many other have said, the first one is just [...new Set(arr)]
For the second, just filter out those that occur more than once:
const arr = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10];
const count = (arr, e) => arr.filter(n => n == e).length
const unique = arr => arr.filter(e => count(arr, e) < 2)
console.log(unique(arr));
var arr = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10];
var map = {};
var finalResult = [];
for (var i = 0; i < arr.length; i++) {
if (!map.hasOwnProperty(arr[i])) {
map[arr[i]] = true;
finalResult.push(arr[i]);
}
}
//if you need it sorted otherwise it will be in order
finalResult.sort(function(a, b) {
return a - b
});
console.log(finalResult);
I want to do bulk delete from an array using typescript.
I did it by using for loop.
this.versions = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
this.selectedVersions = [1, 2, 3, 4, 5, 6];
for (let i = 0; i < this.selectedVersions.length; i++) {
this.versions = this.removeObjectFromArray(this.versions, this.selectedVersions[i]);
}
//removing a object from array
removeObjectFromArray(listOfdata: any, data: any) {
let index = listOfdata.findIndex(function (o) {
return o === data;
})
listOfdata.splice(index, 1);
return listOfdata;
}
But I don't like to use for loop.so let me know how to do bulk delete in array using typescript.
You can just use array filter:
var versions = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
var selectedVersions = [1, 2, 3, 4, 5, 6];
versions = versions.filter(el => !selectedVersions.includes(el));
console.log(versions);
Use a filter
// will only keep elements that are not included in selectedVersions
this.versions = this.versions.filter(i => !this.selectedVersions.includes(i));
Make use of array.filter and filter the contents of the arrays based on the condition
let versions = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
let selectedVersions = [1, 2, 3, 4, 5, 6];
versions = versions.filter(arrayVal => selectedVersions.indexOf(arrayVal) == -1 );
// checks for the values of selected Versions agains each value of versions and returns accordindly
console.log(versions)
I think you can use indexOf, like this:
this.versions = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
this.selectedVersions = [1, 2, 3, 4, 5, 6];
for (let i = 0; i < this.selectedVersions.length; i++)
{
if(this.versions.indexOf(this.selectedVersions[i])!==-1){
this.versions.splice(index, 1);
}
}
I would personally use a filter for this to preserve the original arrays:
let nonSelectedVersions = this.versions.filter((e) => this.selectedVersions.indexOf(e) !== -1);
Use array.filter() instead of for loop
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
Typescript is the same as javascript, you can us all your knowledges from JS.
How do I remove a particular element from an array in JavaScript?
You can use for-of loop as well, if you TS compiler support
var versions = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
var selectedVersions = [1, 2, 3, 4, 5, 6];
for ( val of selectedVersions) {
if(selectedVersions.indexOf(val)!=-1){
versions.splice(versions.indexOf(val), 1);
}
}