I want to make array that contain numbers into new array which has sum result of two by two.
For example, if there is number array like below
const arrayOne = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
I want to change it like below
const newArrayOne = [1, 5, 9, 13, 17]
other example is
const arrayTwo = [10, 11, 12, 13, 14, 15]
const newArrayTwo = [21, 25, 29]
How can I achieve this?
You could take flatMap and return every second sum.
var array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
pairs = array.flatMap((v, i, a) => i % 2 ? [] : [v + (a[i + 1] || 0)]);
console.log(pairs);
You can simply do it with for iteration.
const arrayOne = [10, 11, 12, 13, 14, 15, 17]
const result = [];
for(var i = 0; i < arrayOne.length; i+=2){
const sum = arrayOne[i] + ((i + 1 < arrayOne.length) ? arrayOne[i + 1] : 0);
result.push(sum);
}
console.log(result)
let array = [ 1, 3, 5, 7, 9, 11]
let newArray = []
for (let i =0; i < array.length; i = i + 2){
newArray.push(array[i] + array[i+1])
}
console.log(newArray)
You can use reduce:
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
const output = arr.reduce((a, e, i) => (a[a.length - 1] += e, i % 2 && i !== arr.length - 1 && a.push(0), a), [0])
console.log(output)
Or, you could chunk the array, then add the elements together:
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
const output = arr.reduce((a, _, i) => (i % 2 === 0 && a.push(arr.slice(i, i + 2)), a), [])
.flatMap(([a,b]) => a + b)
console.log(output)
Related
How to divide this array:- [0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 13, 14, 15] into two different arrays with one set of consecutive sequences in one array and another set of consecutive in another array.
for eg : array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 13, 14, 15]
Desired output [0, 1, 2, 3, 4, 5, 6, 7, 8] and [12, 13, 14, 15]
The array should split into a number of consecutive sequences present in the array. If there are 3 consecutive sequences then the array should split into 3 different arrays with consecutive values and so on.
Another example = [1 ,2 ,3 ,4 5, 14, 15, 16, 22, 23, 24, 25]
Desired output [1, 2, 3, 4, 5] and [14, 15, 16] and [22, 23, 24, 25]
let arrnew = [0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 13, 14, 15]
let arr2 = []
for (let j = 0; j < arrnew.length; j++) {
if (arrnew[j + 1] - 1 === arrnew[j]) {
arr2.push(arrnew[j])
}
}
Tried this but not working.
var arr = [1,2,3,4,6,7,8,9,10]
var result = []
for (var i = 0; i < arr.length; i++) {
if (i === 0) {
result.push([arr[0]])
} else if (arr[i] != arr[i-1] + 1) {
result.push([arr[i]])
} else {
tmp = result[result.length - 1]
tmp.push(arr[i])
result[result.length - 1] = tmp
}
}
console.log(result) // [ [ 1, 2, 3, 4 ], [ 6, 7, 8, 9, 10 ] ]
Here we loop through arr. For the first element, the only thing we need to do is append to result a new array with the first number.
Now, for every number after the first one, if the current number is not equal to the previous number + 1, we need to append a new array to result that contains the current number. Otherwise, we simply append the current number to the last array in result.
const arr = [1, 2, 3, 4, 5, 14, 15, 16, 22, 23, 24, 25];
const canSplit = (arr = []) => {
const count = arr.reduce((acc, num) => {
acc[num] = (acc[num] || 0) + 1
return acc
}, {})
const needed = {}
for (const num of arr) {
if (count[num] <= 0) {
continue
}
count[num] -= 1
if (needed[num] > 0) {
needed[num] -= 1
needed[num + 1] = (needed[num + 1] || 0) + 1
} else if (count[num + 1] > 0 && count[num + 2]) {
count[num + 1] -= 1
count[num + 2] -= 1
needed[num + 3] = (needed[num + 3] || 0) + 1
} else {
return false
}
}
return true
}
console.log(canSplit(arr));
My array is:
const arr = [1, 4, 8, 10, 5, 7, 5, 9, 7, 5, 44, 6]
This is how you could go about sorting your array:
const arr = [1, 5, 7, 44, 5, 9, 4, 5, 9, 10, 6, 7, 8];
const uniqueArr = arr.filter(function(item, idx, self) {
return self.indexOf(item) == idx;
})
const sortedArr = uniqueArr.sort(function(a, b) {
return a - b;
});
console.log(sortedArr);
const arr = [1, 4, 8, 10, 5, 7, 5, 9, 7, 5, 44, 6];
arr.sort((a,b) => {return a - b;});
let len = arr.length;
const unique = [];
for(let i = 0; i < len; i++){
if(unique.indexOf(arr[i]) === -1){
unique.push(arr[i]);
}
}
console.log(unique);
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);
//I am trying to learn/understand to create a one-dimensional array which contains, in exact order, the array indices used to access a given number within a multi dimensional array
var multiDimensionalArray = [1, 2, 3, [4, 5, 6, [7, 8, 9, [10, 11, 12, [13, 14, [15]]]]]];
// to access 15...
fifteen = multiDimensionalArray[3][3][3][3][2][0];
// Define the variable 'indexArray' here:
indexArray = fifteen.join();
//join method does not work for me. I have tried concat, slice, indexOf methods. Can't seem to be able to find the solution for this part. HELP!
// This will log your variables to the console
console.log(fifteen); //15
console.log(indexArray); //[3, 3, 3, 3, 2, 0]
You can use a recursive function :
var multiDimensionalArray = [1, 2, 3, [4, 5, 6, [7, 8, 9, [10, 11, 12, [13, 14, [15]]]]]];
const getIndex = (arr, num) => {
const path = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
path.push(i);
path.push(getIndex(arr[i], num));
break;
}
if (arr[i] === num) {
path.push(i);
break;
}
}
return path.flat();
};
const indexArray = getIndex(multiDimensionalArray, 15);
console.log(indexArray);
Another approach with a recursive function:
var multiDimensionalArray = [1, 2, 3, [4, 5, 6, [7, 8, 9, [10, 11, 12, [13, 14, [15]]]]]];
const find = (node, needle) => {
const index = node.indexOf(needle);
const nextIndex = node.findIndex(Array.isArray);
return [].concat(...
(index !== -1)
? [index]
: [nextIndex, find(node[nextIndex], needle)]
);
};
const result = find(multiDimensionalArray, 15);
console.log(result);
You could take a recursive approach and return either an empty array fro a not found value or the indices.
function getIndices(array, value) {
var subIndices = [],
index = array.findIndex(v => v === value || Array.isArray(v) && (subIndices = getIndices(v, value)).length);
return index === -1
? []
: [index, ...subIndices];
}
var array = [1, 2, 3, [4, 5, 6, [7, 8, 9, [10, 11, 12, [13, 14, [15]]]]]]
console.log(getIndices(array, 15));
console.log(getIndices(array, 42));
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);