Selecting elements from an array based on another array values in JavaScript - javascript

Sorry for this basic question... I am relatively new to JS.
I have two arrays and want to select values from one based on the values of the other.
For example, if I have
var student = [10, 11, 21, 30, 31, 14];
var class = [1, 1, 2, 3, 3, 1];
How would I proceed (ideally with filter and/or map) to get the list of student numbers in class = 1, for example.
I know how I would do it with a for-loop and push() function, but I think there should be a more elegant/concise way to perform that task in a single line command with map, filter or other functions.
Thanks in advance for any help.

Filtering the students by checking the index in the other array would be pretty simple:
var student = [10, 11, 21, 30, 31, 14];
var classes = [1, 1, 2, 3, 3, 1];
console.log(
student.filter((_, i) => classes[i] === 1)
);
Keep in mind you cannot use class as a variable name - it's reserved. Use something else.

class is a reserved word in JavaScript. To achieve the expected output, you can use .filter to return elements where classes[index] have the value of 1:
const students = [10, 11, 21, 30, 31, 14];
const classes = [1, 1, 2, 3, 3, 1];
const getStudentsInClassOne = (arr=[]) => {
if(arr.length !== classes.length) return;
return arr.filter((e,index) => classes[index]===1);
}
console.log( getStudentsInClassOne(students) );

Related

how to write a program that prints the largest value that occurs simultaneously in both arrays?

I have to create two 10-elements arrays with random values from 1 to 20 and write a program that prints the largest value that occurs simultaneously in both arrays.
I created two tabs like below. The program should prints the largest value that occurs simultaneously in both arrays. Here it should be 11. I know just how to catch the max value from the array. I appreciate help.
<script>
var max = 0;
var tab = [1, 2, 5, 8, 9, 11, 15, 16, 17, 20];
var tab2 = [3, 4, 6, 7, 10, 11, 12, 13, 14, 18];
for (var i = 0; i < tab.length; i++) {
if (max <= tab[i]) {
max = tab[i];
}
}
console.log(max);
</script>
to find the largest value use nested loops to compare each element of both arrays as follow
var tab = [1, 2, 5, 8, 9, 11, 15, 16, 17, 20];
var tab2 = [3, 4, 6, 7, 10, 11, 12, 13, 14, 18];
var max = 0;
for (var i = 0; i < tab.length; i++) {
for (var j = 0; j < tab2.length; j++) {
if (tab[i] === tab2[j] && tab[i] > max) {
max = tab[i];
}
}
}
console.log(max);
I'd do this:
// const {intersection,max} require('lodash/fp'}
const { intersection, max } = _;
const tab = [1, 2, 5, 8, 9, 11, 15, 16, 17, 20];
const tab2 = [3, 4, 6, 7, 10, 11, 12, 13, 14, 18];
const res = max(intersection(tab, tab2))
console.log({
intersection: intersection(tab, tab2),
max: max(intersection(tab, tab2)),
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
You can translate that into straight javascript, especially if it's for a homework assignment :).
The approach is as follows ...
get the intersection of both arrays
get the maximum value of the just computed intersection
... which then boils down either to coming up with an own implementation of an intersection functionality or to making use of a third party library / helper functionality.
The below example code features one possible implementation of getIntersection which makes use of ...
Array.from in order to always ensure the processing of array parameters,
Array.prototype.sort in order to help optimally assign the participating arrays for the best computation performance,
Array.prototype.reduce and a Map instance for creating a lookup-table in order to achieve a more performant filter process when it comes to the actual computation of the intersection,
Array.prototype.filter and Map.prototype.has for finally computing the intersection result.
function getIntersection(firstIterable = [], secondIterable = []) {
const [
comparisonBase, // ... compare to the shorter array.
comparisonList, // ... filter from the longer array.
] = [Array.from(firstIterable), Array.from(secondIterable)]
// - ensure two arrays (line above)
// - and sort them according to each array's `length`.
.sort((a, b) => a.length - b.length);
// create a `Set` based lookup from the shorter array.
const itemLookup = new Set(comparisonBase);
// the intersection is the result of following filter task.
return comparisonList.filter(item => itemLookup.has(item));
}
const tab = [1, 2, 4, 5, 8, 9, 11, 15, 16, 17, 20, 21, 0];
const tab2 = [3, 4, 6, 7, 9, 10, 11, 12, 13, 14, 18, 19, 0];
console.log(
'intersection of `tab` and `tab2` ...',
getIntersection(tab, tab2)
);
console.log(
'max value of the intersection of `tab` and `tab2` ...',
Math.max(...getIntersection(tab, tab2))
);

does python have an equivalent to javascript's every and some method?

I was trying to search the docs for a method similar but I was only able to find pythons all() and any(). But that's not the same because it just checks if the val is truthy instead of creating your own condition like in js' every and some method.
i.e
// return true if all vals are greater than 1
const arr1 = [2, 3, 6, 10, 4, 23];
console.log(arr1.every(val => val > 1)); // true
// return true if any val is greater than 20
const arr2 = [2, 3, 6, 10, 4, 23];
console.log(arr2.some(val => val > 20)); // true
Is there a similar method that can do this in python?
Just combine it with a mapping construct, in this case, you would typically use a generator expression:
arr1 = [2, 3, 6, 10, 4, 23]
print(all(val > 1 for val in arr1))
arr2 = [2, 3, 6, 10, 4, 23]
print(any(val > 20 for val in arr2))
Generator comprehensions are like list comprehensions, except they create a generator not a list. You could have used a list comprehension, but that would create an unecessary intermediate list. The generator expression will be constant space instead of linear space. See this accepted answer to another question if you want to learn more about these related constructs
Alternatively, albeit I would say less idiomatically, you can use map:
arr1 = [2, 3, 6, 10, 4, 23]
print(all(map(lambda val: val > 1, arr1)))
arr2 = [2, 3, 6, 10, 4, 23]
print(any(map(lambda val: val > 20, arr2)))
Yes, Python has it.
numbers = [1, 2, 3, 4, 5]
all_are_one = all(elem == 1 for elem in numbers)
some_are_one = any(elem == 1 for elem in numbers)

how to split an array according to their difference in value

I have an ordered array like the following:
const arrayToSplit = [1, 3, 5, 8, 10, 12, 21, 23];
which I want to be split into multiple arrays where the difference between one and another is max a value, let us say 2:
const result = [
[1, 3, 5],
[8, 10, 12],
[21, 23]
];
or 8:
const result = [
[1, 3, 5, 8, 10, 12],
[21, 23]
];
and so forth. I have a solution but is far away from an elegant one, where I run the array by using an accumulator variable. Is there a neater, more elegant solution?
A possible solution to this:
function splitArray(arrayToSplit = []){
const explodedArray = [];
let elementsNewArray = [];
for(const element of arrayToSplit) {
if(elementsNewArray.length == 0) {
elementsNewArray.push(element);
continue;
}
if(element - _.last(elementsNewArray)) <= 2) {
elementsNewArray.push(element);
} else {
explodedArray.push(elementsNewArray);
elementsNewArray = [element];
}
}
explodedArray.push(elementsNewArray);
return explodedArray;
}
It seems reasonably straightforward to simply keep track of the last item iterated over in a variable. When iterating, check if the difference between that and the current item being iterated is larger than the limit. If it is, push a new array. Regardless. push the item being iterated over to the last array in the collection.
const arrayToSplit = [1, 3, 5, 8, 10, 12, 21, 23];
const maxDiff = 2;
const result = [[arrayToSplit[0]]];
let last = arrayToSplit[0];
for (const item of arrayToSplit.slice(1)) {
if (item - last > maxDiff) result.push([]);
result[result.length - 1].push(item);
last = item;
}
console.log(result);

Return Multiple items with the .filter() method - JavaScript

If I have an array with a set of numbers, and want to remove certain ones with the .filter method, I understand how to do this in when i need to remove a single item (or if i can use a mathematical expression), but can't get it to work with multiple items either purely by their value or position in the array.
In the following code I would like the new array selection to return the numbers 10, 12, 15
Also, I do need to do this with the filter() method only.
JS
let random = [4, 10, 12, 15, 30];
let selection = random.filter(function(num){
return num === [10, 12, 30];
});
You can use includes:
let random = [4, 10, 12, 15, 30, 10, 10, 12, 5];
let selection = random.filter(function(num){
var good = [10, 12, 30]
return good.includes(num);
});
console.log(selection)
Of if you prefer the terseness of arrow function:
let random = [4, 10, 12, 15, 30, 10, 10, 12, 5];
let selection = random.filter(num => [10, 12, 30].includes(num))
console.log(selection)
Forgive me if I do not understand it correctly, but if what you're looking for is to filter an array by the item's index, you can use the second parameter passed to the filter method's callback, which is the index.
let random = [4, 10, 12, 15, 30];
let selection = random.filter(function(num, index){
return index > 0 && index < 4;
});
console.log(selection);
You do need a condition that will return true or false when using filter, so the simplest way to do this with the filter method would be:
let random = [4, 10, 12, 15, 30];
let selection = random.filter(function(num){
if (num > 4 && num < 16) {return true};
});
The other way to do it would be filtering by position in the array and that would be better achieved with other array methods.
If I understand your question you want a function that takes a an array, checks if the elements are in your larger array and if they are there, removes them.
Filter might not be your best choice here because it doesn't alter the original array, it only makes a new array. Try using splice.
let random = [4, 10, 12, 15, 30];
function remove(array) {
for (var i = 0; i < array.length; i++) {
if(random.includes(array[i])){
random.splice(random.indexOf(array[i]), 1)
}
}
}
remove([10, 12, 30]);
console.log(random); // [4, 15]
I am assuming you want to remove because if you already know which elements you want why filter them out? why not just pass them into your function as a new array? filter will create a new array anyways.
But if you would like to remove elements from your first array the answer above might help.

interchange array using shift method

I am trying to interchange array and print it using shift method but not sure whether I can use it or not.
Code Snippet below.
var points = [40, 100, 1, 5, 25, 10];
//trying to achieve like anotherPoints array
//var anotherPoints = [1, 5, 100, 40, 25, 10];
for (index = 0; index < points.length; index++) {
points.shift();
console.log(points);
}
Some logic to get the desired result:
var points = [40, 100, 1, 5, 25, 10],
temp1 = [], temp2 = [], anotherArray;
points.forEach(function(val){
if(val < 10 ) {
temp1.push(val)
} else {
temp2.push(val);
}
});
anotherArray = temp1.sort().concat(temp2.sort(function(a,b){return b- a}));
alert(anotherArray);
It's not possible via shift or splice. Unless manually creating the array.
The shift() method doesn't shift or interchange the elements of an Array. It is similar to pop(), but it pops out the first element from the Array.
For example,
var points = [40, 100, 1, 5, 25, 10];
console.log(points.shift()); // 40
console.log(points); // [100, 1, 5, 25, 10]
As to your requirement of rearranging the elements of an Array, you will have to use Array.splice() method. Check out this question Reordering arrays.

Categories