Get elements from an array based on array containing indices - javascript

I have two arrays:
1- inventory that contains some elements
2- indices_dates that contains the indices of the elements I want from inventory.
Is there a simple way to create an array formed by the elements of inventory if their index is contained into indices_dates
Example:
let inventory
let indices_dates
let final = []
inventory = [25, 35, 40, 20, 15, 17]
indices_dates = [0, 2, 3, 5]
---Some Code To Get Final Array---
The output I would like:
final = [25, 40, 20, 17]
I did the following:
let inventory
let indices_dates
let final = []
let i
inventory = [25, 35, 40, 20, 15, 17]
indices_dates = [0, 2, 3, 5]
for (i in indices_dates) {
final.push(inventory[indices_dates[i]])
}
But I am wondering if there is another, more direct way to achieve it.

You can use Array.map() to iterate the indices array, and take the values from inventory:
const inventory = [25, 35, 40, 20, 15, 17]
const indices_dates = [0, 2, 3, 5]
const final = indices_dates.map(idx => inventory[idx])
console.log(final)

You can do as #Ori suggest or alternative solution is :
Another approach is using forEach :
const inventory = [25, 35, 40, 20, 15, 17]
const indices_dates = [0, 2, 3, 5];
let final = [];
indices_dates.forEach(data => final.push(inventory[data]))
console.log(final)
Using for of :
const inventory = [25, 35, 40, 20, 15, 17]
const indices_dates = [0, 2, 3, 5];
let final = [];
for (let dateIndex of indices_dates){
final.push(inventory[dateIndex])
}
console.log(final)

Related

How to sum values ​in nested arrays

I have array
const array1 = [[5, 10, 15], [1, 2, 3]];
How can I get such a summed array from it?
const sum = [6, 12, 18];
I am assuming that you have same format as you shown here.
const array1 = [[5, 10, 15], [1, 2, 3]];
const newArray = array1[0].map((i, index) => {
return i + array1[1][index]
})
console.log(newArray, "newArray")
const array1 = [[5, 10, 15], [1, 2, 3]];
result=[]
for(let i =0;i<array1.length;i++){
for(let j=0;j<array1[i].length;j++){
if(!result[j]){
result[j]=array1[i][j];
}else{
result[j]+=array1[i][j];
}
}
}
console.log(result);

Create new array of objects based on two arrays in Javascript

I want to get the array of objects created from two simple arrays:
const array1 = [20, 2, 35, 86]
const array2 = [8, 86, 15, 23, 35, 44]
The expected result:
const result = [
{ id: 20, value: false },
{ id: 2, value: false },
{ id: 35, value: true },
{ id: 86, value: true },
];
The array1 length is the one that matters. So I need to find matched values in both arrays as showed in the expected result.
Thank you very much for your help.
You can combine map with includes:
array1.map(i => ({id: i, value: array2.includes(i)}))
Should be simple. Loop through the first array using Array.map & return an object.
const array1 = [20, 2, 35, 86]
const array2 = [8, 86, 15, 23, 35, 44]
const result = array1.map(i => ({ id: i, value: array2.includes(i) }))
console.log(result)
Create a set from the second array:
const a2set = new Set(array2);
then map your first array:
array1.map(v1 => ({id:v1, value: a2set.has(v1)}))
Start a loop against first array and check if that element exists in second array or not.
If element exists push it to array containing objects with flag true or else as false.
const array1 = [20, 2, 35, 86]
const array2 = [8, 86, 15, 23, 35, 44]
var objArray = []
array1.forEach(function(elem){
objArray.push({
id : elem,
value : array2.indexOf(elem) != -1 ? true : false
});
});
console.log(objArray);
You can use array indexOf to find if the item is inside the second array.
const array1 = [20, 2, 35, 86];
const array2 = [8, 86, 15, 23, 35, 44];
let output = [];
array1.forEach((number) => {
output.push({
id: number,
value: array2.indexOf(number) !== -1
});
});
console.log(output);
Try a simple for loop:
const array1 = [20, 2, 35, 86];
const array2 = [8, 86, 15, 23, 35, 44];
var res = [];
for (var i = 0; i < array1.length; i++) {
if (array2.includes(array1[i])) {
res.push({ id: array1[i], value: true });
} else {
res.push({ id: array1[i], value: false });
}
}
console.log(res);
Try the following. If performance is important, or if the arrays might include a large amount of elements, I'd consider using sets for better lookup performance.
const array1 = [20, 2, 35, 86]
const array2 = [8, 86, 15, 23, 35, 44]
const result = array1.map(element => {
return {
id: element,
value: array2.includes(element)
};
})

How to find a max value for any quantity of arrays?

I need to find Max values for any number of arrays within the function. For example, user can add 1 array or 10 arrays. Output should show max values for each of the arrays.
Currently, my code works only if 1 array is provided.
Please let me know what is wrong.
function getMaxs(args){
array = args;
var max = array[0];
for(i = 0; i < array.length; i++){
if(max < array[i]){
max = array[i];
}
}
console.log(max);
return max;
}
getMaxs([5, 6, 7], [18, 19, 20], [5, 7, 3, 10]); // output is 7
getMaxs([5, 6, 7]); // output is 7
getMaxs([18, 19, 20], [5, 10, 74, 394]); // output is 20
If you need a max for every provided array:
const getMaxs = (...args) => args.map(arr => Math.max(...arr));
console.log( getMaxs([5, 6, 7], [18, 19, 20], [5, 7, 3, 10]) ); // [7, 20, 10]
console.log( getMaxs([5, 6, 7]) ); // [7]
console.log( getMaxs([18, 19, 20], [5, 10, 74, 394]) ); // [20, 394]
If you don't care which sub-array the result comes from, you can use Array.prototype.flat:
function getMaxs(array) {
const flatArray = array.flat();
return Math.max(...flatArray);
}
const arr = [[5, 6, 7], [18, 19, 20], [5, 7, 3, 10]];
const max = getMaxs(arr);
console.log(max);
I believe you're looking for rest parameters.
Something along these lines:
function getMaxs(...arrays) {
return Math.max(...arrays.flat());
}
// usage
getMaxs([5, 6, 7], [18, 19, 20], [5, 7, 3, 10]); // output is 20
getMaxs([5, 6, 7]); // output is 7
getMaxs([18, 19, 20], [5, 10, 74, 394]); // output is 394
Related: The arguments object in case you can't use rest parameters. In that case, you probably don't support flat either, which in that case I'll recommend you to look for a polyfill somewhere.
You can use the .flat() function, so the arrays would merge and become one, like this:
function getMaxs(args){
array = args.flat();
//it will now see it as one big array
....
}
But, the .flat() function may not work on older browsers, so you may also do this:
array = args.reduce((acc, val) => acc.concat(val), [])
The effect will be the same.
Iraklis solution is fine, but it suppose you give an array of arrays. However, if you want to pass arrays as separated arguments, you could use the Spread syntax and Rest parameters:
function getMaxs(...arrays) {
const max = Math.max(...arrays.flat())
console.log(max) // DEBUG
return max
}
getMaxs([5, 6, 7], [18, 19, 20], [5, 7, 3, 10])
getMaxs([5, 6, 7])
getMaxs([18, 19, 20], [5, 10, 74, 394])
Of course, you should be careful about browser compatibility:
function getMaxs(...args) {
array = args.flat();
var max = array[0];
for (i = 0; i < array.length; i++) {
if (max < array[i]) {
max = array[i];
}
}
// console.log(max);
return max;
}
console.log(getMaxs([5, 6, 7], [18, 19, 20], [5, 7, 3, 10]));
console.log(getMaxs([5, 6, 7]));
console.log(getMaxs([18, 19, 20], [5, 10, 74, 394]));
the above one will be the solution for your question. You can check the below screenshots for your reference.
For this input i have added screen shots for your reference how it will process the code
getMaxs([5, 6, 7], [18, 19, 20], [5, 7, 3, 10])
now it will take the whole
[![enter image description here][1]][1]

To create a one-dimensional array which contains, in order, the array indices used to access a number in the given variable

//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));

Wrap items in an array with a character

I have an array [1, 5, 20, 17, 6, 12, 13, 20, 1, 14, 20].
Whenever the element of the array is equal to 20 I would like to wrap it with an asterisk on either side like this [1, 5, *20*, 17, 6, 12, 13, *20*, 1 , 14, *20*].
How can I achieve this?
You can use map
let arr = [1, 5, 20, 17, 6, 12, 13, 20, 1, 14, 20]
let result = arr.map(o => o === 20 ? '*20*' : o);
console.log(result);
Doc: map()
You can use Arrays forEach to modify the elements of the array. elem is each element and i is the respective index. We are using forEach to modify the existing array. Since this is what you desired..
let arr = [1, 5, 20, 17, 6, 12, 13, 20, 1, 14, 20]
arr.forEach((elem, i) => {
if (elem === 20) {
arr[i] = "*20*"
}
})
console.log(arr)
function rollDice(max, times, bonus) {
var rolls = [1, 5, 20, 17, 6, 12, 13, 20, 1, 14, 20];
rolls.forEach((elem, i) => { if (elem === 20) { rolls[i] = "twenty" } });
for (var i = 0; times > i; i++)
{
max = Math.floor(max);
rolls.push(Math.floor(Math.random() * max) + 1 | + parseInt(bonus));
}
console.log(rolls);
}
rollDice(20, 5);
The problem you are experiencing is that you need to convert the integer number into strings. JavaScript has several ways to cleverly do this behind-the-scenes, but if you are still gaining an understanding of that, it's better to be explicit about what data types you start with (integers), and what data types you expect to end with (strings).
You transform the array, "mapping" over each item, transforming it to a string, and then if the string matches "20", you add the asterisks.
const start_array = [1, 5, 20, 17, 6, 12, 13, 20, 1, 14, 20];
const new_array = start_array.map((integer) => {
let number_string = integer.toString();
if (number_string === "20") {
number_string = "*" + number_string + "*";
}
return number_string;
})
console.log(new_array);

Categories

Resources