JavaScript Copy of Arrays [duplicate] - javascript

This question already has answers here:
Copy array by value
(39 answers)
Closed 2 years ago.
I'm trying to eliminate the minimum and maximum values from the below array and create 2 new arrays without the maximum and minimum values
array = [4, 6, 7, 8, 9]
const indOmin = 0,
indOm = 5
minArr = arr
maxArr = arr
minArr.forEach(cur => {
if (arr.indexOf(cur) === indOmin) {
minArr.splice(indOmin, 1)
}
})
maxArr.forEach(cur => {
if (arr.indexOf(cur) === indOm) {
maxArr.splice(indOm, 1)
}
})
When I use...
console.log(minArr)
console.log(maxArr)
...then in both cases it returns [6, 7, 8, 9].
But instead of...
minArr = arr
maxArr = arr
...if I use...
minArr = arr.map(cur => cur = cur)
maxArr = arr.map(cur => cur = cur)
... then the arrays return expected values.
[6, 7, 8, 9]
[4, 6, 7, 8]
Please help me understand why it doesn't work when I explicitly use the = operator (minArr = arr).

Change
minArr=arr; maxArr=arr;
To
minArr=[...arr]; maxArr=[...arr];
It doesn't work because array doesn't copy with = you had reference of same array in both minarr and maxarr.

Related

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, convert an array of double into an array of pair of doubles [duplicate]

This question already has answers here:
Split array into chunks
(73 answers)
Closed 2 years ago.
Suppose that you have an array of doubles in Javascript:
double_arr = [1, 2, 3, 4, 5, 6, 7, 8]
What is the most efficient way to convert it into an array of arrays with 2 doubles like above:
double_arr = [[1,2], [3,4], [5,6], [7,8]]
You can iterate skipping one index in each iteration, like this:
const double_arr = [1, 2, 3, 4, 5, 6, 7, 8];
const result = [];
for (let i = 0; i < double_arr.length; i += 2)
result.push([ double_arr[i], double_arr[i+1] ]);
console.log(result);

How to create a table every X element in a table? [duplicate]

This question already has answers here:
Split array into chunks
(73 answers)
How to put each element of array into table row - table data?
(1 answer)
Closed 3 years ago.
sorry I don't speak English very well.
I have a table with several elements, I want to return all the X elements a new table inside a table.
For example:
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
let newArr = [
[1,2,3],
[4,5,6],
[7,8,9],
[10,11,12],
];
This is the way I am currently doing this :
const size = shuffleImages.length / 4
while (shuffleImages.length > 0) {
columns.push(shuffleImages.splice(0, size))
}
I would like to understand how to do this without using while and instead use for example .map or is there just an easier way to do this?
You need to split the array into small array using map and than slice it :
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
var chunkSize = 3;
const groups = arr.map( function(e,i){
return i%chunkSize===0 ? arr.slice(i,i+chunkSize) : null;
}).filter((e) =>e);
console.log(groups);

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) : [];
}

How to take every 3rd element of an array [duplicate]

This question already has answers here:
Javascript: take every nth Element of Array
(6 answers)
Closed 6 years ago.
I have an array, and want to return only every third element as a new array (starting at 0).
For example:
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let newArr = [1, 4, 7];
This is the way I am currently doing this:
let newArr = [];
for(let x = 0; x < arr.length; x += 3) {
newArr.push(arr[x]);
}
return newArr;
Is there a way to do this with arr.map? Is there just an easier way to do this?
You can alternatively do it with a filter,
let newArr = arr.filter((_,i) => i % 3 == 0);
But remember, using basic for loop is bit more efficient than others in some contexts.

Categories

Resources