I want to get values from an array of arrays, and I'm having difficulties doing it.
I have the following:
var id = 1; //value I want to use for the search
var _restrictions = [[1, 2], [2, 4], [5, 1], [1, 6]]; //arrays that I want to check
var arrVal = [];
By using the id, I want to retrieve all of the values, inside the arrays, where the id exits and store them in the array "arrVal".
For example:
_restrictions = [[1, 2], [2, 4], [5, 1], [1, 6]];
//arrVal will be: [2, 5, 6], because the id existing inside the arrays [1,2],
//[5,1] and [1,6]
The "_restrictions" array is a array of arrays that contain restrictions. They are independent values (the first one isn't the index or id).
How can I do that?
Thanks in advance!
Here's a version that will work for any size of nested array. It returns an flattened array of all values not including the id.
var id = 1;
var _restrictions = [[1, 2, 9], [2, 4], [5, 1], [1, 6]];
var arrVal = _restrictions.reduce((acc, c) => {
// Find the index of the id in each nested array
const i = c.findIndex(arr => arr === id);
// If it exists, splice it out and add it
// to the accumulator array
if (i > -1) {
c.splice(i, 1);
acc.push(...c);
}
return acc;
}, []);
console.log(arrVal);
EDIT: Updated code after the question is edited.
The question lacks a bit of clarity. I am assuming you want to filter the sub-arrays which have id in them i.e. contains the value 1.
let id = 1; //value I want to use for the search
let _restrictions = [[1, 2], [2, 4], [5, 1], [1, 6]];
let arrVal = _restrictions.filter((item) => {
return item.includes(id);
});
let new_array = arrVal.concat.apply([], arrVal).filter(x => x !== id);
console.log(new_array);
// [2, 5, 6]
Related
This question already has answers here:
How to check if an array contains another array?
(6 answers)
javascript search array of arrays
(12 answers)
Closed 3 months ago.
How I can scan my array within array if there is equal array element.
I want to check if its true or false
// the array to be scan
const array = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
]
// the new array
const newArray = [0, 1, 2]
Based on anwser from how-to-compare-arrays-in-javascript,you just need to iterate the first array and then compare them
const array = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
]
// the new array
const newArray1 = [0, 1, 2]
const newArray2 = [0, 1, 3]
const checkArray = (array1,array2) => {
for(let arr of array1){
if(arr.length === array2.length && arr.every((v,i) => v === array2[i])){
return true
}
}
return false
}
console.log(checkArray(array,newArray1))
console.log(checkArray(array,newArray2))
You can use every method to check all the items.
array.filter((arr)=>arr.every((item,index)=>newArray[index]===item))
run a foreach or for loop with a combination of name.find(x => x.ref === value);
or use array.filter((arr)=>arr.every((item,index)=>newArray[index]===item))
const array = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
];
const newArray = [0, 1, 2]
let isPresent = false;
for (let i = 0; i < array.length; i++) {
if (JSON.stringify(array[i]) == JSON.stringify(newArray)) {
isPresent = true
break
}
}
console.log(isPresent)
After stringifying the array you are able to compare directly in js and If it matches I changed the boolean value to true.
In case you have any doubts feel free to comment.
Given an array of arrays, I want to get the averages of each subarray, and then output which subarrays have the same average. The output will not repeat the subarrays, but just the indices where they occur in the input array.
So for this input:
[
[3, 3, 4, 2], // index 0: average = 3
[4, 4], // index 1: average = 4
[4, 0, 3, 3], // index 2: average = 2.5
[2, 3], // index 3: average = 2.5
[3, 3, 3], // index 4: average = 3
];
The expected output is:
[[0, 4], [1], [2, 3]]
...because the subarrays at indices 0 and 4 have the same average, while the subarray at index 1 has an average that is not shared by another subarray, and finally the subarrays at indices 2 and 3 have the same average.
I completed the function as we see below, and the averages are calculated correctly, but I can't get the values of the object sorted with keys in distinct arrays...
function solution(a) {
let b = [];
let entier = {};
a.filter((elt, cle) => {
let s = a[cle].reduce((prevalue, curvalue) => prevalue + curvalue, 0);
b[cle] = s / a[cle].length;
//console.log(s/a[cle].length)
entier[cle] = s / a[cle].length;
});
console.log(entier);
let arrNew = Object.entries(entier);
console.log(arrNew);
}
let a = [
[3, 3, 4, 2],
[4, 4],
[4, 0, 3, 3],
[2, 3],
[3, 3, 3],
];
solution(a); // [[0, 4], [1], [2, 3]]
How can I make my code work?
With this:
entier[cle] = s / a[cle].length;
...you are assigning the average as a value associated with the current index as the key. But you need the opposite. You'll want to group by the average, so that must be the key, and the index must be the value (but as an array).
So change that to:
(entier["x" + (s / a[cle].length)] ??= []).push(cle);
The "x" is to ensure that the key is not an integer as then different rules apply for the ordering of that key in the object. By prepending this "x", we ensure that keys are ordered in the order they are created.
The ??= assignment ensures that the property is initialised as an array when it didn't exist yet.
The second correction is here: Object.entries should be Object.values as you are no longer interested in those "x" keys.
function solution(a) {
let entier = {};
a.filter((elt, cle) => {
let s = a[cle].reduce((prevalue, curvalue) => prevalue + curvalue, 0);
(entier["x" + (s / a[cle].length)] ??= []).push(cle);
});
let arrNew = Object.values(entier);
console.log(arrNew);
}
let a = [
[3, 3, 4, 2], // 0: 3
[4, 4], // 1: 4
[4, 0, 3, 3], // 2: 2.5
[2, 3], // 3: 2.5
[3, 3, 3], // 4: 3
];
solution(a); // [[0, 4], [1], [2, 3]]
I have an array of 3 value arrays, and I need to convert them into a set of arrays where each array is made up of the values which were common between arrays, so my input of
[[2,3,9], [1,4,7], [3,6,9], [1,7,5], [7,5,8], [9,6,10], [3,6,10], [1,8,5]]
becomes
[[2,3,6,9,10],[1,4,5,7,8]]
Order is not important. I've found similar questions such as Group same values in an array within an array in JS but it seems slightly different to my case, but I imagine using reduce is the way to go, but I don't entirely understand how. I have tried creating an object using the following format, but couldn't get from there to an answer:
{
vertex: 3,
triangles: [2,3,9], [3,6,9], [3,6,10]
}
Here is one algorithm. Take first item from array and check first item array has any common array. If they have common item, then merge it and move the merged array to first item of array. If no common item, then add to result array.
const merge = (arr) => {
const result = [];
while (arr.length > 0) {
let first = arr.shift();
const idx = arr.findIndex((items) =>
items.some((item) => first.includes(item))
);
if (idx !== -1) {
first = first.concat(arr[idx]);
arr.splice(idx, 1);
arr.unshift(first);
} else {
result.push(first);
}
}
return result.map(items => [...new Set(items)]);
};
const data = [
[2, 3, 9],
[1, 4, 7],
[3, 6, 9],
[1, 7, 5],
[7, 5, 8],
[9, 6, 10],
[3, 6, 10],
[1, 8, 5],
];
console.log(merge(data));
I have an array with pairs of numbers and need to find matching pairs within the array
numberStore = [ [0,0],[1,1],[1,2],[1,3],[1,4],[1,5]... ]
I want to be able to find 1,4. Is there a way to find this array without relying on numberStore[4]?
Since you need to perform this search frequently, I would build a hashed set to avoid mapping and searching over and over. For example
const numberStore = [ [0,0],[1,1],[1,2],[1,3],[1,4],[1,5] ]
const hashedSet = new Set(numberStore.map(pair => pair.toString()))
// looks like ["0,0", "1,1", "1,2", "1,3", etc]
console.log([...hashedSet])
const search = (find) => {
return hashedSet.has(find.toString())
}
console.info('Find [1,4]', search([1,4]))
console.info('Find [4,1]', search([4,1]))
I've used Array.prototype.toString() as the hashing function but you could substitute anything there that creates a unique and comparable entity for each pair.
Use Array.prototype.find():
var numberStore = [
[0, 0],
[1, 1],
[1, 2],
[1, 3],
[1, 4],
[1, 5]
];
var oneFour = numberStore.find(function([a, b]) {
return a == 1 && b == 4;
});
console.log(oneFour);
Or if you prefer ES6 arrow syntax:
var numberStore = [
[0, 0],
[1, 1],
[1, 2],
[1, 3],
[1, 4],
[1, 5]
];
var oneFour = numberStore.find(([a, b]) => a == 1 && b == 4);
console.log(oneFour);
Another alternative is using the method some() to test elements for a condition.
var numberStore = [
[0,0],
[1,1],
[1,2],
[1,3],
[1,4],
[1,5]
];
var exists = numberStore.some(([a, b]) => a === 1 && b === 4);
console.log(exists ? "Pair [1,4] exists" : "Pair [1,4] don't exists");
I've got an array such as:
var foo = [1, 2, 3, 4, 5];
and I would like to map it to:
var bar = [[1,2], [2,3], [3,4], [4,5], [5,1]];
I do not need to handle scenarios where the length of foo is 0 or 1.
My naive approach is:
var foo = [1, 2, 3, 4, 5];
var bar = _.map(foo, function(value, index) {
return index < foo.length - 1 ? [value, foo[index + 1]] : [value, foo[0]];
});
console.log(bar);
<script src="https://cdn.jsdelivr.net/lodash/3.10.1/lodash.js"></script>
I'm wondering if there's a more clear way to express this mapping.
Using plain simple lodash. First drop the first element from the array, append it, and then zip it with the original array:
var a = [1,2,3,4,5]
var b = _.zip(a, _.concat(_.drop(a), a[0]))
The result:
console.log(b)
[[1, 2], [2, 3], [3, 4], [4, 5], [5, 1]]
_.nth
Gets the element at index n of array. If n is negative, the nth element from the end is returned.
just get sibling in reverse order
var bar = _.map(foo, function(val, index) {
return [val, _.nth(foo, (index + 1) - foo.length)];
});