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)];
});
Related
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.
If i have an array A = [1, 4, 3, 2] and B = [0, 2, 1, 2] I want to return a new array (A - B) with values [1, 2, 2, 0]. What is the most efficient approach to do this in javascript?
const A = [1, 4, 3, 2]
const B = [0, 2, 1, 2]
console.log(A.filter(n => !B.includes(n)))
Use map method
The map method takes three parameters in it's callback function like below
currentValue, index, array
var a = [1, 4, 3, 2],
b = [0, 2, 1, 2]
var x = a.map(function(item, index) {
// In this case item correspond to currentValue of array a,
// using index to get value from array b
return item - b[index];
})
console.log(x);
For Simple and efficient ever.
Check here : JsPref - For Vs Map Vs forEach
var a = [1, 4, 3, 2],
b = [0, 2, 1, 2],
x = [];
for(var i = 0;i<=b.length-1;i++)
x.push(a[i] - b[i]);
console.log(x);
const A = [1, 4, 3, 2]
const B = [0, 2, 1, 2]
const C = A.map((valueA, indexInA) => valueA - B[indexInA])
console.log(C) // [1, 2, 2, 0]
Here the map is returning the substraction operation for each number of the first array.
Note: this will not work if the arrays have different lengths
If you want to override values in the first table you can simply use forEach method for arrays forEach. ForEach method takes the same parameter as map method (element, index, array). It's similar with the previous answer with map keyword but here we are not returning the value but assign value by own.
var a = [1, 4, 3, 2],
b = [0, 2, 1, 2]
a.forEach(function(item, index, arr) {
// item - current value in the loop
// index - index for this value in the array
// arr - reference to analyzed array
arr[index] = item - b[index];
})
//in this case we override values in first array
console.log(a);
One-liner using ES6 for the array's of equal size in length:
let subResult = a.map((v, i) => v - b[i]); // [1, 2, 2, 0]
v = value, i = index
function subtract(operand1 = [], operand2 = []) {
console.log('array1', operand1, 'array2', operand2);
const obj1 = {};
if (operand1.length === operand2.length) {
return operand1.map(($op, i) => {
return $op - operand2[i];
})
}
throw new Error('collections are of different lengths');
}
// Test by generating a random array
function getRandomArray(total){
const pool = []
for (let i = 0; i < total; i++) {
pool.push(Math.floor(Math.random() * total));
}
return pool;
}
console.log(subtract(getRandomArray(10), getRandomArray(10)))
Time Complexity is O(n)
You can also compare your answer with a big collection of arrays.
It seems correct for me, but it doesn't work:
var arr = [1, 2, 3, 4, 5];
var bar = [2, 4];
arr = arr.filter(function(v) {
for (var i; i < bar.length; i++) {
return bar.indexOf(v);
}
});
console.log(arr); // []
// expected: [1, 3, 5]
How this will work, and how to do the same work with map?
Array#filter iterates over the array, you don't need for inside filter
The problem with for inside filter is that it'll return the index of the element, which could be -1(truthy) if not found and anything upto the length of array. And only for the first element i.e. index zero, filter will not add the element as zero is falsey in JavaScript.
Also, the for loop will only check if the first element of the bar and return from there.
var arr = [1, 2, 3, 4, 5];
var bar = [2, 4];
arr = arr.filter(function(v) {
return bar.indexOf(v) === -1;
});
console.log(arr);
document.write('<pre>' + JSON.stringify(arr, 0, 4) + '</pre>');
You don't need Array#map, map will transform the array elements with keeping the same number of elements.
ES6:
Since ES6 you can use Array#includes, and arrow functions to make your code look cleaner:
let arr = [1, 2, 3, 4, 5];
let bar = [2, 4];
arr = arr.filter(v => !bar.includes(v));
console.log(arr);
document.write('<pre>' + JSON.stringify(arr, 0, 4) + '</pre>');
I have an array like
var arr = [ [1, 4, 5],
[2, 6, 7],
[3, 3, 9]]
I would like to get the row which has max value in column 2, so in this example row 2. How can I do this in javascript?
Edit: I can do it using a for loop which iterates over all rows and have a temp max variable to keep track of the max. But I was hoping for a more efficient way.
Thanks
Well, iterating and keeping a temporary max variable is probably the most efficient way of doing it, but if you want a way that looks more pleasing, you can try something like:
var col2 = arr.map(function (elem) {
return elem[1]; //to get all the column 2 values
});
var index = col2.indexOf(Math.max.apply(this, col2));
Edit: If you want to use the index of the last found element in case of a tie, use
col2.lastIndexOf(Math.max.apply(this, col2));
The below code will give you the highest number:
var array = [[1, 4, 5],
[2, 6, 7],
[3, 3, 9]];
var bigNum = 0;
for(var i=0;i<array.length; i++){
var largest = Math.max.apply(Math, array[i]);
if(largest > bigNum) {
bigNum = largest;
}
}
console.log(bigNum);
How about this
var arr = [[1, 4, 5], [2, 6, 7], [3, 3, 9]],
t;
$.each(arr, function(k, v){
t = !t ? v[1] : (v[1] > t ? v[1] : t);
});
console.log(t);
Nothing can out better plain loop version, but you can use Array.prototype.reduce like this
var arr = [ [1, 4, 5], [2, 6, 7], [3, 3, 9]], col = 1;
var best = arr.reduce(function(tillNow, current) {
if (tillNow.best < current[col]) {
tillNow.best = current[col];
tillNow.row = current;
}
return tillNow;
}, {best:0, row:[]});
console.log(best.row); # [ 2, 6, 7 ]
console.log(best); # { best: 6, row: [ 2, 6, 7 ] }
Reduce function accepts the till now value as the first parameter and the current element as the second parameter.
For the first element, parameters will be like this
tillNow : {best:0, row:[]} : current: [1, 4, 5]
We compare current's indented column with tillNow.best. If current's is bigger than tillNow, the best element and the current row will be set in tillNow and that will be returned which will be fed back into the reduce's next iteration as tillNow. So, in our case, on the second iteration, values change like this
tillNow : {best:4, row: [1, 4, 5]} : current: [2, 6, 7]
And on third iteration,
tillNow : {best:6, row: [2, 6, 7]} : current: [3, 3, 9]
And finally the result will be
{ best: 6, row: [ 2, 6, 7 ] }
Please try this.
var col2 = [];
var max = 0;
$.each(arr, function(i, val){
col2.push(val[1]);
})
max = Math.max.apply( Math, col2 );
This example returns runs map over over each row and returns an array with the each row's number from the nominated column. It then returns the index of the highest number in that array.
function findRowForMaxInCol(arr, col) {
var column = arr.map(function(el) { return el[col]; });
var highest = Math.max.apply(null, column);
return column.indexOf(highest);
}
console.log(findRowForMaxInCol(arr, 1)); // 1
Fiddle.
Just iterating through the array and checking if the second element is largest. The variable large will contain the row i and the largest value e.
var arr = [ [1, 4, 5],
[2, 6, 7],
[3, 3, 9]],
large = {i:0, e: 0}; // i: row, e: largest elem
arr.map(function (a, idx) {
if (a[1] > large.e) {
large.e = a[1];
large.i = idx;
}
});
console.log(large); // {i: 1, e: 6}. row: 1 and element 6.
Generalizing the problem: find the element in an array which has the maximum 'f(x)':
var findMax = function(array, f){
var element = null;
var max = -Infinity;
for (var i=0; i!=array.length; ++i){
var value = f(array[i]);
if (value > max){
element=array[i];
max=value;
}
};
return element;
};
And apply the general algorithm to rows with a function returning the second element of the row:
var secondElement= function(row){ return row[1]; };
var max = findMax(rows, secondElement);
(JSFiddle)