Related
How can I compare values in arrays:
['1', '2', '3', '4']
['2', '1', '4', '1']
just like:
if (1 > 2) return counter++,
first with first, second with second, third with third. If i do for loops i will do it many more times:
for (let i = 0; i < arr1.length; i++) {
for (let j = 0; j < arr2.length; j++) {
if (Number(arr1[i]) > Number(arr2[j])) {
counter++;
}
}
}
i just want to compare them only once, each key value with each key value. So in this example, counter should be 2
You can use Array.reduce to compare the element of the first array with the second one.
Use 0 as a initial value of the accumulator/counter.
Check if the element of the first array passed in as the second
argument of the reduce callback is greater than the corresponding
element of the second array.
If the the above is true increment the accumulator.
const arr1 = ['1', '2', '3', '4'];
const arr2 = ['2', '1', '4', '1'];
const count = arr1.reduce((accumulator, element, idx) => {
return +arr2[idx] > +element? accumulator + 1 : accumulator;
}, 0);
console.log(count);
Just use 1 for loop like below. Since the arrays have the same length, you can just use the index from the first loop for both.
var arr1 = ['1', '2', '3', '4'];
var arr2 = ['2', '1', '4', '1'];
for (var i = 0; i < arr1.length; i++) {
if (arr1[i] > arr2[i]) {
console.log(arr1[i]);
}
}
You need a single loop and compare the values at the same index.
var array1 = ['1', '2', '3', '4'],
array2 = ['2', '1', '4', '1'],
i,
counter = 0;
for (i = 0; i < array1.length; i++) {
if (+array1[i] > +array2[i]) {
counter++;
}
}
console.log(counter);
You don't need a nested loop for that. You can do that using only single loop.However a cleaner way is using Array.prototype.filter() and getting its length.
let arr1 = ['1', '2', '3', '4']
let arr2 = ['2', '1', '4', '1']
let count = arr1.filter((a,i) => +a > +arr2[i]).length;
console.log(count)
I'm looking for a simple method to iterate over an array and generate a result like below... Better if someone can show me how to do this in the ES2015 way.
var numbers = ['one', 'two', 'three'];
/* Expected result */
/*
0: ['one', 'two', 'three'],
1: ['one', 'two'],
2: ['one']
*/
https://jsfiddle.net/minuwan/1eL83sbz
You could map the sliced array.
var numbers = ['one', 'two', 'three'],
result = numbers.map(function (_, i, a) {
return a.slice(0, a.length - i);
});
console.log(result);
You can use slice to get the output you want instead of using pop since it will modify your numbers array
var numbers = ['one', 'two', 'three'];
var array = [];
var arrayLength = numbers.length;
for (var i = 0; i < arrayLength; i++) {
array[i] = numbers.slice(0, arrayLength - i);
}
console.log(array);
or you would simply use map with slice
var numbers = ['one', 'two', 'three']
var array = numbers.map(function (_, i) {
return numbers.slice(0, numbers.length - i);
});
console.log(array);
Let’s assume we have this two arrays:
x = [1, 2, 3];
y = ['a', 'b'];
What would be the best way to combine them and get the following result:
newArray = ['1a', '1b', '2a', '2b', '3a', '3b'];
Here is one way of doing that:
x.reduce(function(arr, x) {
return arr.concat(y.map(function(y) {
return x + y;
}));
}, []);
//=> ["1a", "1b", "2a", "2b", "3a", "3b"]
Try this:
var x = [1, 2, 3];
var y = ['a', 'b'];
var output = [];
for (var i = 0; i < x.length; i++) {
for (var j = 0; j < y.length; j++) {
output.push(x[i]+y[j]);
}
}
document.getElementById('output').innerHTML = JSON.stringify(output);
<div id="output"></div>
Try this..
var x = [1, 2, 3];
var y = ['a', 'b'];
var newarr = [];
for(var i=0;i<x.length;i++){
for(var j=0;j<y.length;j++){
newarr.push(x[i]+y[j]);
}
}
//alert(newarr);
DEMO
If arrow functions are supported you obtain the desired result like this:
[].concat.apply([],
x.map(x => y.map(y => x+y))
);
If not, you have to write it like this
[].concat.apply([],
x.map(function(x) { return y.map(function(y) {return x+y })})
);
Explanation:
The middle line yields the following result:
[ ["1a", "1b"], ["2a", "2b"], ["3a", "3b"] ]
Then the Array.prototype.concat method is used to concatenate the inner arrays.
You could simply create a array to be returned and do a simple loop for the array that contains numbers. Inside of that loop, you create another loop for the array of combinations to the numbers (var b=0,e=comb.length;e>b;b++). Using the i from the first loop (for(var i=0,l=array.length;l>i;i++)) you push the array at it (a[i]) with the array of combinations at the position b (c[b]) (inside of the loop that's inside of the first loop) to the new array. Finally, return the new array.
function CombineExample(a,c){
var New=[];
for(var i=0,l=a.length;l>i;i++){
for(var b=0,e=c.length;e>b;b++){
New.push(a[i]+c[b])
}
}
return New
}
Clean! And do this to use:
CombineExample([1,2,3],['a','b'])
/* returns ["1a", "1b", "2a", "2b", "3a", "3b"] */
Use nested loops to iterate all elements of the participating arrays. Populate new array elements inside the inner loop:
var x = [1, 2, 3];
var y = ['a', 'b'];
var newArray = [];
x.forEach(function(xItem) {
y.forEach(function(yItem) {
newArray.push(xItem.toString().concat(yItem));
});
});
console.log(newArray);
The simplest approach:
var x = ["a", "b", "c"];
var y = [1, 2, 3];
var newArray = [];
var i = 0;
for (;i < x.length;++i) {
var j = 0;
for (;j < y.length;++j) {
newArray.push(x[i] + y[j]);
}
}
;
Please do note that if both arrays are numeric, this will actually add the numbers, not concatenate. You'd need to do some string conversion.
var x = [1, 2, 3];
var y = ['a', 'b'];
var z = [];
for(var i=0;i<x.length;i++){
for(var j=0;j<y.length;j++){
z.push(x[i]+y[j]);
}
}
Are you seriously asking for that?
Given two arrays, one with keys, one with values:
keys = ['foo', 'bar', 'qux']
values = ['1', '2', '3']
How would you convert it to an object, by only using underscore.js methods?
{
foo: '1',
bar: '2',
qux: '3'
}
I'm not looking for a plain javascript answer (like this).
I'm asking this as a personal exercise. I thought underscore had a method that was doing exactly this, only to find out it doesn't, and that got me wondering if it could be done.
I have an answer, but it involves quite a few operations. How would you do it?
I know you asked for Underscore.js solutions, but you don't need it for this. Here's a oneliner using ES7 object spread operator and dynamic keys.
keys.reduce((obj, k, i) => ({...obj, [k]: values[i] }), {})
Using ES6:
let numbers = [1, 2, 3],
names = ["John", "Mike", "Colin"];
let a = Object.assign({}, ...numbers.map((n, index) => ({[n]: names[index]})))
console.log(a);
What you need to use is the _.object method of underscore js.
If object method is not present in your version of underscore.js then you will have to manually add this method to it.
keys = ['foo', 'bar', 'qux']
values = ['1', '2', '3']
_.object = function(list, values) {
if (list == null) return {};
var result = {};
for (var i = 0, l = list.length; i < l; i++) {
if (values) {
result[list[i]] = values[i];
} else {
result[list[i][0]] = list[i][1];
}
}
return result;
};
console.log(_.object(keys, values))
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
Given that this is 4 years old, and Lodash has more or less taken the place of Underscore, I thought I would share this solution using Lodash:
var keys = ['foo', 'bar', 'qux'];
var values = ['1', '2', '3'];
var obj = _.zipObject( keys, values );
Simple and clean.
How about:
keys = ['foo', 'bar', 'qux'];
values = ['1', '2', '3'];
some = {};
_.each(keys,function(k,i){some[k] = values[i];});
To be complete: another approach could be:
_.zip(['foo', 'bar', 'qux'],['1', '2', '3'])
.map(function(v){this[v[0]]=v[1];}, some = {});
For the record, without underscore you could extend Array.prototype:
Array.prototype.toObj = function(values){
values = values || this.map(function(v){return true;});
var some;
this .map(function(v){return [v,this.shift()]},values)
.map(function(v){this[v[0]]=v[1];},some = {});
return some;
};
// usage
var some = ['foo', 'bar', 'qux'].toObj(['1', '2', '3']);
See jsfiddle
var toObj = (ks, vs) => ks.reduce((o,k,i)=> {o[k] = vs[i]; return o;}, {});
var keys=['one', 'two', 'three'],
values = [1, 2, 3];
var obj = toObj(keys, values);
console.log(obj);
Cleanest is
keys = ['foo', 'bar', 'qux']
values = ['1', '2', '3']
function Arr2object(keys, vals) {
return keys.reduce(
function(prev, val, i) {
prev[val] = vals[i];
return prev;
}, {}
);
}
console.log(Arr2object(keys, values));
Or, use _.reduce, but if you're using underscore you already have _.object.
What you are looking for is the zip function.
zip function
Edit:
It doesn't create an object but it does combine the array by creating a sub array
There's no function that exactly does what you want. But you can use the result of zip to create your object.
var arr = _.zip(['foo', 'bar', 'qux'], ['1', '2', '3']);
var i, len = arr.length;
var new_obj = [];
for(i=0; i<len; ++i)
new_obj[arr[i][0]] = arr[i][1];
This question already has answers here:
Merge keys array and values array into an object in JavaScript
(14 answers)
Closed 9 years ago.
Is there a common Javascript/Coffeescript-specific idiom I can use to accomplish this? Mainly out of curiosity.
I have two arrays, one consisting of the desired keys and the other one consisting of the desired values, and I want to merge this in to an object.
keys = ['one', 'two', 'three']
values = ['a', 'b', 'c']
var r = {},
i,
keys = ['one', 'two', 'three'],
values = ['a', 'b', 'c'];
for (let i = 0; i < keys.length; i++) {
r[keys[i]] = values[i];
}
console.log(r);
.as-console-wrapper { max-height: 100% !important; top: 0; }
keys = ['one', 'two', 'three']
values = ['a', 'b', 'c']
d = {}
for i, index in keys
d[i] = values[index]
Explanation:
In coffeescript you can iterate an array and get each item and its position on the array, or index.
So you can then use this index to assign keys and values to a new object.
As long as the two arrays are the same length, you can do this:
var hash = {};
var keys = ['one', 'two', 'three']
var values = ['a', 'b', 'c']
for (var i = 0; i < keys.length; i++)
hash[keys[i]] = values[i];
console.log(hash['one'])
console.log(hash.two);