How to map only every second value in array - javascript

I have some array of numbers:
var arr = [1, 7, 1, 4];
I want to increase only every first value, such that the expected output would be: [2, 7, 2, 4]
I tried some combination of map and filter but I don't understand how it can work together...
var mapuj = arr.map(x => x *2);

You can use map() and use second argument which is idnex to determine if it's at event index or not
let arr = [1, 7, 1, 4];
let output = arr.map((n, index) => index % 2 === 0 ? n * 2 : n);
console.log(output);

Related

How to use javascript map to combine numbers at every nth element?

I like to combine numbers at every 4th index of an array. In the following oversimplified example, I did using "for" loop. Instead of that, I like to learn how to use "map" to achieve the same result. Thanks for any help!
function test() {
var array = [1, 2, 3, 4, 5, 6, 7, 8], arrayNew = [];
for (var n = 0; n < 4; ++n)
arrayNew[n] = array[n] + array[n + 4];
console.log(arrayNew)
}
To use .map, you could iterate the slice of the array that omits the first four elements. During that iteration, the loop index will be 4 units less, so you can grab array[i] and combine it with the currently iterated value from the slice:
const array = [1, 2, 3, 4, 5, 6, 7, 8];
const result = array.slice(4).map((val, i) => array[i] + val);
console.log(result);
If you want to add more than just two values, but want to also add the value at 2n, 3n, ...etc, then you need a nested loop. Here .map is of less use. I would "map" with the use of Array.from, which has a callback function that performs a mapping. Secondly, the sum that has a dynamic number of terms can be performed with reduce:
function accumulate(array, n) {
const groups = Array.from({length: array.length / n});
return Array.from({length: n}, (val, i) =>
groups.reduce((sum, _, j) => sum + array[i + j*n], 0)
);
}
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
console.log(accumulate(array, 4));

Javascript get array element from the condition of summation of array element

I have an Array, arr = [2,4,8,7,3,6] I want to make each element of it be summation when the result is 10 , then save the element it would be arranged to another array.
make the element that result is 10 close each other like 2 and 8, add to another element named arr2.
result i need : arr2[2,8,3,7,4,6]
my code :
const arr = [2, 4, 8, 7, 3, 6];
let arr2 = [];
for (let i = 0; i < arr.length(); i++) {
let Number1 = arr[i];
let Number2 = arr[(i + 1)];
if (Number1 + Number2 === 10) {
let element1 = arr.indexOf(Number1);
let element2 = arr.indexOf(Number2);
arr2.push(element1, element2);
}
console.log(arr2[i]);
}
someone can solve my problem please ?
If you need to create arr2 so that the items sum up to 10 you can make use of a simple map here:
const arr = [2, 4, 8, 7, 3, 6];
const arr2 = arr.map((item) => 10 - item)
console.log(arr2);
You should first loop through the array to create a dictionary of value to index, then loop the array again and lookup for the complement of the current value to the target. If it exist then yes you got the answer.
.filter(x => x > i) is to search for complement that has higher index than current one so that we will not get duplicated result pushed. For example input is [2, 8], you don't want to get [2, 8, 8, 2]
Here is my solution
const arr = [2, 4, 8, 7, 3, 6];
let arr2 = [];
function solution(target: number, input: number[]): number[] {
const result: number[] = [];
const lookUpMap: {[key: number]: number[]} = {};
let i = 0;
for (const each of input) {
if (!(each in lookUpMap)) {
lookUpMap[each] = [];
}
lookUpMap[each].push(i);
i++;
}
i = 0;
for (const each of input) {
const difference = target - each;
if (difference in lookUpMap) {
const complementIndex = lookUpMap[difference].filter(x => x > i)[0];
if (complementIndex) {
result.push(input[i], input[complimentingIndex]);
}
}
i++;
}
return result;
}
arr2 = solution(10, arr);
console.log(arr2);
Assuming a valid result can be created for the given arr. A fairly simple solution would be to sort the array first. Then step through half the array and take the element on the current index, and the element on the inverse index (length - 1 - index). And push() those both in the resulting array.
So here in steps, given you have the following array:
[2, 4, 8, 7, 3, 6]
You sort it:
[2, 3, 4, 6, 7, 8]
Then you step through half the indexes and take each element, and the element on the inverse index.
[2, 3, 4, 6, 7, 8]
// \ \ \/ / /
// \ ------ / -> [2, 8, 3, 7, 4, 6]
// ----------
const arr = [2, 4, 8, 7, 3, 6];
const sortedArr = Array.from(arr).sort((a, b) => a - b); // ascending
const length = sortedArr.length;
const nPairs = length / 2;
const arr2 = [];
for (let i = 0; i < nPairs; ++i) {
arr2.push(
sortedArr[i],
sortedArr[length - 1 - i],
);
}
// or if you want a more functional approach:
// const arr2 = Array.from({ length: nPairs }).flatMap((_, i) => [sortedArr[i], sortedArr[length - 1 - i]]);
console.log(arr2);
Do note that this is probably not the fastest solution, because sorting is non-linear.
Obviously this solution does not work if an invalid input is given, like [7,2,1,8] which can never produce a valid output.

Javascript (ES6) way to select/filter objects from and array and remove them from original array [duplicate]

This question already has answers here:
Dividing an array by filter function
(14 answers)
Closed 4 years ago.
Is there a way to filter an array of objects to retrieve an array of the values I need but also remove the filtered values from the original list. Something like this
let array = [1, 2, 3, 4, 5];
const filteredList, listContainingRemainingValues = array.filter(value => value > 3);
Output:
filteredList = [4, 5];
listContainingRemainingValues = [1, 2, 3];
Is there any built in functionality to do this already in Javascript or will i have to roll my own?
You could take an array as temporary storage for the wanted result.
const
array = [1, 2, 3, 4, 5],
[remaining, filtered] = array.reduce((r, v) => (r[+(v > 3)].push(v), r), [[], []]);
console.log(filtered);
console.log(remaining);
Same with lodash's _.partition
const
array = [1, 2, 3, 4, 5],
[filtered, remaining] = _.partition(array, v => v > 3);
console.log(filtered);
console.log(remaining);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
Here's one option:
const array = [1, 2, 3, 4, 5];
// Get all the indices we want to keep:
const matchingIndices = array
.map((v, i) => [i, v > 3])
.filter((el) => el[1])
.map((el) => el[0]);
// Filter the input array by indices we want/don't want
const matching = array.filter((v, i) => matchingIndices.indexOf(i) >= 0);
const nonMatching = array.filter((v, i) => matchingIndices.indexOf(i) < 0);
Use 2 filters
let array = [1, 2, 3, 4, 5];
let filteredList = array.filter(value => value > 3);
let listContainingRemainingValues = array.filter(f => !filteredList.includes(f))
console.log(filteredList)
console.log(listContainingRemainingValues)
Here's one of the way using underscore library:
var data = [1, 2, 3, 4, 5]
var x = _.reject(data, function(num){ return num > 3; });
var y = _.difference(data, x);
console.log(x);
console.log(y);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
Sort the array, find the index of your threshold value and then splice it in order to remove the elements from the input array and to return the removed elements:
const array = [1, 2, 3, 4, 5];
// just if the input array is not already sorted
array.sort();
const removedElements = removeAndGet(array, 3);
console.log('input array:', array);
console.log('removed elements:', removedElements)
function removeAndGet(input, thresholdValue) {
const ind = input.findIndex(a => a > thresholdValue);
return ind > -1 ? input.splice(ind) : [];
}

Condition inside forEach

I have two arrays:
firstArray = [1, 2, 3, 4];
secondArray = [5, 6, 7, 8];
I must use their elements to compute another one inside a forEach.
_.forEach(firstArray, (data, i) => {
myValue: firstArray[i] + secondArray[i]
});
This works fine. But I want to ignore the last element of the second array all the time. So in this case, for i = 3 the result should be 4, not 4+8, ignoring the last value of the second array.
I know that using an if statement wouldn't work but is there a way to do it?
I mean inside the forEach, removing the last element before the function doesn't work in this case.
UPDATE: I received some good answers but all of them were using something different than forEach. I would like to know if there is a way to do it with this function or not.
You can just check if i is the last element of the second array using array.length.
I don't really understand your forEach code, but you could use ternary operators in it:
_.forEach(firstArray, (data, i) => {
myValue: firstArray[i] + (i === secondArray.length - 1 ? 0 : secondArray[i])
});
You could reduce and map the arrays.
var firstArray = [1, 2, 3, 4],
secondArray = [5, 6, 7, 8],
result = [firstArray, secondArray].reduce((a, b) => a.map((v, i) => v + b[i]));
console.log(result);
I would do this:
firstArray = [1, 2, 3, 4];
secondArray = [5, 6, 7, 8];
for (let i = 0; i < firstArray.length; i++){
if(i === firstArray.length - 1) {
myValue = firstArray[i];
} else {
myValue = firstArray[i] + secondArray[i]
}
}
Use map
firstArray = [1, 2, 3, 4];
secondArray = [5, 6, 7, 8];
var output = firstArray.map( ( s, i, ar ) => s + (i == ar.length - 1 ? 0 : secondArray[i] ) );
UPDATE: I received some good answers but all of them were using
something different than forEach. I would like to know if there is a
way to do it with this function or not.
using forEach, you would need another array to capture the sum
firstArray = [1, 2, 3, 4];
secondArray = [5, 6, 7, 8];
var myValue = [];
firstArray.map( ( s, i, ar ) => myValue.push( s + (i == ar.length - 1 ? 0 : secondArray[i] ) ) );
now myValue is
[6, 8, 10, 4]
Hence map seems to be a less-verbose approach.

Adding pairs of numbers in array with reduce (javascript)

Given a 2D array, I want to add the last number of the preceeding inner array to the first number of the next inner array.
I managed to get up to the point where:
var output= [[1,2,3],[4,5,6],[7,8,9],[1,2,3]] //this becomes...
output = [3,4,6,7,9,1] (edited typo)
I now would like to add the pairs up to return this array:
output = [9, 11, 10]
So far, this is what I have, and it returns [3,6,4,7,9,1]. I would like to see how reduced can be used for this, but also interested in how a for loop would accomplish the same thing.
var output= [[1,2,3],[4,5,6],[7,8,9],[1,2,3]]
output = output
.reduce((newArr,currArr)=>{
newArr.push(currArr[0],currArr[currArr.length-1]) //[1,3,4,6,7,9]
return newArr
},[])
output.shift()
output.pop()
return output
Can use index argument of reduce
let output= [[1,2,3],[4,5,6],[7,8,9],[1,2,3]];
output = output
.reduce((newArr, currArr, i, origArr) => {
if (i > 0) {
let prevArr = origArr[i - 1];
newArr.push(currArr[0] + prevArr[prevArr.length - 1]);
}
return newArr
}, [])
console.log(output)
Not clear what should occur at last element of input array? You can use for..of loop, Array.prototype.entries() to sum values of specific index of arrays.
let output = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[1, 2, 3]
];
let res = Array.from({
length: output.length - 1
});
for (let [key, value] of output.entries()) {
if (key < output.length - 1)
res[key] = value[value.length - 1] + output[key + 1][0]
}
console.log(res)
You could do something like this, using reduce.
var input = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[1, 2, 3]
];
let output = [];
input.reduce((prevArr, currentArray) => {
if (prevArr) {
output.push(prevArr[prevArr.length - 1] + currentArray[0]);
}
return currentArray;
});
console.log(output);

Categories

Resources