Javascript checking only the first item of an array - javascript

I have an array of arrays, i.e. [ [1,2], [1,3] ] and I want to check if is there any 1 as the first element of a subarray. It doesn't matter if it is a [1,2] or [1,3]. I'm interested only in the 1's existence. Sure I could use some loops to do this, but I wonder if is there an elegant "built-in" way to do this in js, something like:
arr.includes([1, _]) // returns true if is there any 1 as first element of an array

some is something you are looking for.
Code example:
const data = [[1, 3], [1, 5]]
const res = data.some( ([a, _]) => a === 1 ) // less elegant alternative:
// .some(e => e[0] === 1)
console.log(res)

Related

Compare two arrays of integers and return an array with all matches

I currently have two arrays with a bunch of ids. I want to compare the two arrays to see what ids match, then return an array with only the matching ids. I've tried multiple approaches, but nothing seems to work so far. This is what I've done:
const filteredIdArray = array1.filter((item) =>
array2(item)
);
const filteredIdArray = array1.filter(
(item) => array2.indexOf(item) !== -1
);
Both attempts were pulled from other examples, and neither is working. I did make sure that my array1 and array2 were actually arrays not objects. Is there something I'm missing here?
Rephrasing, this is array intersection. A terse, readable, quick (1 pass through each array) is (sort of like this)...
const intersect = (a, b) => {
const setB = new Set(b);
return a.filter(el => setB.has(el));
}
console.log(intersect([1,2,3,4], [3,4,5,6]))
There's ambiguity in the question about whether we're aiming for unique matches. This idea returns all matches, including duplicates. To eliminate those, run the result through a set once more. [...new Set(resultWithDups)]
I think in the first approach it should be array2.includes.
const filteredIdArray = array1.filter((item) => array2.includes(item))
Use a intermediate hash object to hold id's as its key.
That would make it easier to find "duplicates" and push to a result.
arr1 = [1, 2, 3, 4, 0]
arr2 = [3, 4, 5, 6, 0]
result = []
hash = {}
arr1.forEach(item => hash[item] = true)
arr2.forEach(item => hash[item] === true && result.push(item))
console.log(result)
You can use Array#filter and Array#includes methods as follows:
const
arr1 = [2,5,6,8,9,10],
arr2 = [3,4,7,6,8,11],
output = arr1.filter(n => arr2.includes(n));
console.log( output );
Also .....
Your second option should work:
const
arr1 = [2,5,6,8,9,10],
arr2 = [3,4,7,6,8,11],
output = arr1.filter(n => arr2.indexOf(n) !== -1);
console.log( output );

Return the biggest number in the array (array contains a string)?

I dont understand why my code is not working, when I read it logically I feel that it should work, but what it does is return 3,4,2 as opposed to the highest number of the 3 (i.e. 4)
const array2 = ['a', 3, 4, 2] // should return 4
for(items of array2){
if(items > 0) {
console.log(Math.max(items));
}
What am I doing wrong? What have I misinterpreted? Please don't give me the answer, just tell me why my logic does'nt work
in for-loop, items is just one item actually. Each time, you print the current item. it is basically the same thing with this
const array2 = ['a', 3, 4, 2] // should return 4
for(items of array2){
if (items > 0) {
console.log(items);
}
}
you can do it with this only
const array2 = ['a', 3, 4, 2] // should return 4
console.log(Math.max(...array2.map(s => +s || Number.MIN_SAFE_INTEGER)));
check out: https://stackoverflow.com/a/44208485/16806649
if it was integer-only array, this would be enough:
const array2 = [3, 4, 2] // should return 4
console.log(Math.max(...array2));
You just need to filter the array.
Below example I am using filter() method of array and then just pass that filteredarray to Math.max() function.
isNan() function returns false for valid number.
Math.max(...filteredArr) is using spred operator to pass the values.
const arr = ['a', 3, 4, 2];
const filteredArr = arr.filter(val => {
if (!isNaN(val)) return val;
})
console.log(Math.max(...filteredArr));
I don't think you need the "For(items of arr)" instead just if the length of the array is greater than 0, then console.log(Math.max(...arr) should work.
See document ion below:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max
It is returning 3,4,2 because you are taking array2, and iterating through with each individual element of the array. items is not the entire array, it is the individual element and that is why Math.max of an individual element is just getting the same value.
just you need fliter you're array then get max value, also in arrayFilters function use to removes everything only return numbers of this array
function arrayFilters(array){
const number = array.filter(element => typeof element === 'number')
return number;
}
function getMaxValue(number){
return Math.max.apply(null,number)
}
const arr = ['a',2,3,4];
console.log(getMaxValue(arrayFilters(arr)))

How to convert an array to multiple array

I have an array abc = [1, 2, 3].
How can i convert it to multiple arrays: [1, 2] , [1, 3], [2, 3]
Note: If abc have n items, we will convert to n*(n-1) arrays
you could do something like this:
const combinations = arr =>
arr.flatMap((elX, indexX) =>
arr
.filter((_, indexY) => indexY == indexX)
.map(elY => [elX, elY])
)
the result will be n*(n-1) so for [1,2,3] = [[1,2],[1,3],[2,1],[2,3],[3,1],[3,2]]
Looks like you want to list all kind of combination to be made from original array
you can run code below in console to check if it fits your needs
Note that in code below, i use filter to avoid same value in the same array group
Sorry for my bad english
let arr = [1, 2, 3];
arr = arr.map((currentValue, index, arr)=>{
return arr.filter((val2, idx2) => val2 !== currentValue);
});
document.write(JSON.stringify(arr,null,4));
Edit: i know the question wants 6 arrays, this code above is following the example he gave... This is alternative answer if what he really meant was to find every single unique combination (without mirror effect)

Remove array from inside array based on index in JS

I have an array which looks like:-
[[0,1], [0,2], [0,3], [1,1], [1,2]...]
I am looking to remove one of the arrays from this array based on the indexOf() but I keep getting a value of -1, which removes the last item from the array when I try the following code:-
array = [[0,1], [0,2], [0,3], [1,1], [1,2]];
console.log('Removed value', array.splice(array.indexOf([0,3]), 1));
console.log('Result', array);
would somebody be able to point me in the right direction to help solve this issue I am having?
Thank you in advance.
You can't use indexOf because when you declare [0,3] in array.splice(array.indexOf([0,3]), 1)) you're creating a new array and this new object is not inside your array (but rather another array that has the same values).
You can use findIndex instead as follows (example):
array.findIndex(x => x[0] === 0 && x[1] === 3)
this will return 2 - now you can use it to delete:
array.splice(2, 1)
If it is OK to remove every occurrence of [0,3], then consider Array.filter combined with array destructuring of the lambda arguments. It offers a slightly leaner syntax than the other solutions.
const input = [
[0,1],
[0,2],
[0,3],
[1,1],
[1,2]
];
const result = input.filter(([x,y]) => !(x==0 && y==3));
console.log('Result=', result);
To explain why your solution will not work:
Comparison operators only work for values not passed by a reference. When dealing references, comparison operators always return false, unless the two references point to the same object. (See this on MDN)
An example:
a = [0,1]
b = a
b === a //true. a and b point to the same array.
a === [0,1] //false. a points to a different array than [0,1]
b[0] = 2
a[0] //2 - b points to the same array as a
To give you a solution (borrows from here)
//Function to compare the values inside the arrays, and determine if they are equal.
//Note: does not recurse.
function arraysEqual(arr1, arr2) {
if(arr1.length !== arr2.length)
return false;
for(var i = arr1.length; i--;) {
if(arr1[i] !== arr2[i])
return false;
}
return true;
}
array = [[0,1], [0,2], [0,3], [1,1], [1,2]];
//Find the index where x has the same values as [0,3]
array.findIndex(x => arraysEqual(x, [0,3])) //2

Find common elements within dynamic array's object elements Javascript

There were a lot of questions asked about this topic, but I couldn't find the answer that addressed directly the issue I am having.
Here is one: Find common elements in 1 array using Javascript
The first difference is that I have a different type of array, its elements are objects with key-value pair, where key is the string and the value is an array of integers.
The second difference is that array is dynamic meaning that sometimes it may have zero elements and the other times it may have 3 object elements.
I am sharing the sample array below:
const array = [
{"key1":[1,2,3]},
{"key2":[2,3,4]},
{"key3":[2,5,6]},
];
The third difference is that the order of elements matters so that final result should output the values of the first element that exist in all subsequent arrays.
The result should be:
const result = [2];
Since 2 is the only common integer of these three elements.
As mentioned array sometimes might have just 1 or 2 or no elements in it and those cases should be accounted.
Edit 1: as asked in the comments the values of array are unique
Since a value can appear in array only once, you can concat the arrays, count the number of appearances, and filter our those that are not equal to the length of the original array.
const findRecuring = (array) =>
[...
[].concat(...array.map((o) => Object.values(o)[0])) // combine to one array
.reduce((m, v) => m.set(v, (m.get(v) || 0) + 1), new Map()) // count the appearance of all values in a map
] // convert the map to array of key/value pairs
.filter(([, v]) => v === array.length) // filter those that don't appear enough times
.map(([k]) => k); // extract just the keys
/** Test cases **/
console.log('Several:', findRecuring([
{"key1":[6,1,2,3,8]},
{"key2":[2,6,3,4,8]},
{"key3":[2,5,6,8]},
]).join());
console.log('None: ', findRecuring([
{"key1":[9,0,11]},
{"key2":[2,6,3,4,8]},
{"key3":[2,5,6,8]},
]).join());
const array = [
{"key1":[1,2,3]},
{"key2":[2,3,4]},
{"key3":[2,5,6]},
];
You could iterate over and store how often a value appears in the array for each value:
var common=new Map();
array.forEach(function(obj){
//var values=new Set(Object.values(obj)[0]);//make unique values out of array
var values=Object.values(obj)[0];//no need for uniqueness as OP states that they are already unique..
values.forEach(function(val){
common.set(val,(common.get(val)||0)+1);
});
});
Now youve got a map with all elements and their appearance in the main array. So now you can simply compare:
var result=[];
common.forEach(function(appearance,el){
if(appearance===array.length){
result.push(el);
}
});
http://jsbin.com/xuyogahija/edit?console
You could get first the arrays in an array without using different keys and then lookup each element if it is in the other array.
let array = [{ key1: [1, 2, 3] }, { key2: [2, 3, 4] }, { key3: [2, 5, 6] }],
result = array
.map(o => o[Object.keys(o)[0]] || [])
.reduce((a, b) => a.filter(c => b.includes(c)));
console.log(result);

Categories

Resources