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");
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.
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]
I have a 3x3 array:
var my_array = [[0,1,2],
[3,4,5],
[6,7,8]];
and want to get the first 2x2 block of it (or any other 2x2 block):
[[0,1],
[3,4]]
with numpy I would have written:
my_array = np.arange(9).reshape((3,3))
my_array[:2, :2]
to get the correct result.
I tried in javascript:
my_array.slice(0, 2).slice(0, 2);
but the second slice affects the first dimension, doing nothing.
Am I doomed to use for loop or is there some new ES6 syntax that would make my life simpler?
Could use a combination of Array.slice and Array.map:
const input = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]
];
const result = input.slice(0, 2).map(arr => arr.slice(0, 2));
console.log(result);
You can use .map() and .slice() methods:
var my_array = [[0,1,2],
[3,4,5],
[6,7,8]];
var result = my_array.slice(0, 2).map(a => a.slice(0, 2));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You could take objects for the indices and for the length of the wanted sub arrays.. Then slice and map the sliced sub arrays.
var array = [[0, 1, 2], [3, 4, 5], [6, 7, 8]],
length = { x: 2, y: 2 },
indices = { i: 0, j: 0 },
result = array.slice(indices.i, indices.i + length.x).map(a => a.slice(indices.j, indices.j + length.y));
console.log(result);
It dont seems to a 3x# array , it is just array of arrays.
You can first use slice to get an array of only first two elements that is
[[0, 1, 2],[3, 4, 5]]
then use reduce to return a new array & inside it get only the first two values
var my_array = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]
];
let x = my_array.slice(0, 2).reduce(function(acc, curr) {
acc.push(curr.slice(0, 2))
return acc;
}, [])
console.log(x)
const input = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]
];
let result =[]
input.forEach(([a, b], index) => {if(index < 2) result.push([a, b])})
console.log(result);
If you are going to work a lot with matrices, then you should check out math.js.
Try the following:
var my_array = [[0,1,2],
[3,4,5],
[6,7,8]];
var matrix = math.matrix(my_array);
var subset = matrix.subset(math.index([0, 1], [0, 1]));
Working example.
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)];
});
I am not sure how to use this to remove duplicate arrays from the main array. so consider the following:
var arr = [
[0, 1],
[0, 1],
[2, 1],
];
The resulting array should look like:
var arr = [
[0, 1],
[2, 1],
];
The documentation makes sense for a single array of elements but not a 2d array.
Ideas?
Update, One small issue with some solutions:
The array to be turned unique might have:
var arr = [
[0, 1]
[0, 2]
[0, 3]
[0, 1]
[2, 1]
]
the array in side the array should have all value compared, so in the above example, it should spit out:
var arr = [
[0, 1]
[0, 2]
[0, 3]
[2, 1]
]
The duplicate being [0, 1]
The easiest way would probably be to use uniq method and then convert the inner arrays to some string representation, JSON.stringify should be good enough solution.
var arr = [[0, 1], [0, 2], [0, 3], [0, 1], [2, 1]]
_.uniq(arr, function(item) {
return JSON.stringify(item);
});
// [[0,1], [0,2], [0,3], [2,1]]
You would use the .uniq function in lodash:
var arr = [
[0, 1],
[0, 1],
[2, 1],
]
var uniqueList = _.uniq(arr, function(item, key, a) {
return item.a;
});
The resulting array will look like:
//var arr = [Object: [0, 1], Object: [2, 1]];
Sure, casting to JSON works, but it feels like we might be wasting resources. I'm using the following Lodash-code in Node.js:
const _ = require("lodash");
var arr = [
[0, 1],
[0, 1],
[2, 1],
];
var uni = _.uniqWith(arr, _.isEqual);
console.log(uni);
Works like a charm, check the Repl here. More on uniqWith at the Lodash docs.
It doesn't use lodash, not optimized I agree :
//remove duplicate array of array of arrays
Array.prototype.uniqueArray = function() {
var uniqObj = {};
this.forEach(function (item) {
uniqObj[JSON.stringify(item)] = 1;
});
var uniqArray = [];
for(var key in uniqObj) {
if (uniqObj.hasOwnProperty(key)) {
uniqArray.push(JSON.parse(key))
}
}
return uniqArray;
};