Multiplying Two Arrays - javascript

I am trying to multiply two arrays, of the same length and create a third array from it.
I've tried loops and I think a nested loop would be the way forward.
Below is my attempt, that multiplied out the whole array
var one = [1, 2, 3, 4, 5];
var two = [1, 2, 3, 4, 5];
//var partOne = one.length
var partOne = []
for(var i=0; i<one.length;i++) {
for(var j=0;j<two.length;j++) {
partOne.push({value:one[i] * two[i]});
}
}
Looking for something similar to the below;
var a = [3, 5]
var b = [5, 5]
//answer
var c = [15, 25]

function multiply(a, b) {
var c = [];
for (var i=0; i<a.length;i++) {
c.push(a[i]*b[i]);
}
return c;
}
var a = [3, 5 ];
var b = [5, 5 ];
var c = multiply(a, b);
console.log(c);
var a = [3, 5 ]
var b = [5, 5 ]
var c = []
for (var i=0; i<a.length;i++) {
c.push(a[i]*b[i]);
}
console.log(c);

let a = [3, 5];
let b = [5, 5];
// x is each element from a
// i is index of a
let c = a.map((x, i) => { return x * b[i]; });
returns
// Array [ 15, 25 ]

Related

in Javascript, how to create the new array using another array

The output that I want to have is newArray = [4, 9, 16, 25]. But I don't get it. Where did I make errors? Please help me.
var array = [2, 3, 4, 5];
var result = [];
function multiply(a) {
return a * a;
}
function newArray (a) {
for (i=0; i<a.lenght; i++){
result.push(multiply(a.value));
}
}
var newArray = newArray(array);
var array = [2, 3, 4, 5];
function multiply(a) {
return a * a;
}
function newArray (a) {
return a.map(multiply)
}
var result = newArray(array);
console.log(result)
This is another way to do it
const array = [2,3,4,5];
function multipliedArray(arr) {
return arr.map(x => x * x);
}
console.log(multipliedArray(array));
Keeping your logic as it is.
You misspelled a.length.
And you missed the index with array a.
var array = [2, 3, 4, 5];
var result = [];
function multiply(a) {
return a * a;
}
function newArray (a) {
for (i=0; i<a.length; i++){ //spelling mistake
result.push(multiply(a[i])); // index should be used
}
return result;
}
console.log(newArray(array));
I found that if I use ES6, I can change the codes like the following.
const arrayPast = [2, 3, 4, 5];
const result = [];
const appendArray = arrayPast.map(x => x * x);
result.push(appendArray);
Another thought, using forEach
const oldArray = [3, 4, 5, 6];
const square = [];
const newArray = oldArray.forEach((x) => square.push(x * x));

get List of values exist more than once in array [duplicate]

This question already has answers here:
How to keep Duplicates of an Array
(4 answers)
Closed 5 years ago.
I have to get a list of values that exist more than once in an array.
This is current code , but as you can see it's too complicated.
var arr = [1, 2, 3, 4, 2, 3];
var flag = {}
var exist2arr = [];
for(var i = 0; i < arr.length; i++){
for(var j = 0 ; j < arr.length; j ++){
if(i !=j && arr[i] == arr[j]){
if(!flag[arr[i]])
exist2arr.push(arr[i]);
flag[arr[i]] = 1;
}
}
}
console.log(exist2arr);
Is there any other way (simple code using javascript built-in function) to achieve this? Any kind of help appreciate.
You could filter the array based on values who's first and current indexes are not equal then run that array through a Set
const arr = [1, 2, 3, 4, 2, 3, 2, 3, 2, 3, 2, 3]; // added in some extras
const filtered = arr.filter((v, i) => arr.indexOf(v) !== i)
const unique = new Set(filtered)
console.info(Array.from(unique)) // using Array.from so it can be logged
var arr = [1, 2, 3, 4, 2, 3];
var o = arr.reduce((o, n) => {
n in o ? o[n] += 1 : o[n] = 1;
return o;
}, {});
var res = Object.keys(o).filter(k => o[k] > 1);
console.log(res);
A bit hacky, but short and O(n):
var arr = [1, 2, 3, 4, 2, 3, 2, 2]
var a = arr.reduce((r, v) => ((r[v + .1] = r[v + .1] + 1 || 1) - 2 || r.push(v), r), [])
console.log( a ) // [2,3]
console.log({ ...a }) // to show the "hidden" items
console.log({ ...a.slice() }) // .slice() can be used to remove the extra items
It could be done like:
function timesInArray(v, a){
var n = 0;
for(var i=0,l=a.length; i<l; i++){
if(a[i] === v){
n++;
}
}
return n;
}
function dups(dupArray, num){
var n = num === undefined ? 2 : num;
var r = [];
for(var i=0,d,l=dupArray.length; i<l; i++){
d = dupArray[i];
if(!timesInArray(d, r) && timesInArray(d, dupArray) >= n){
r.push(d);
}
}
return r;
}
var testArray = [4, 5, 2, 5, 7, 7, 2, 1, 3, 7, 7, 7, 25, 77, 4, 2];
console.log(dups(testArray)); console.log(dups(testArray, 3));

Checking which element is bigger when merging two arrays?

I have two arrays that are the same length, for example var a = [5,2,6,2,7,5]; and var b = [2,3,7,4,3];.
I also have another array which is var c = [0,0,0,0,0];
How do I compare a and b to put the highest element into c which in this case should become [5,3,7,7,5];
ES6 single-line solution:
c = a.map((a, i) => a > b[i] ? a : b[i])
Array#map into a new array, and take the max of the current number from a, and the number with the same index from array b:
const a = [5, 2, 6, 2, 7];
const b = [2, 3, 7, 4, 3];
const c = a.map((num, i) => Math.max(num, b[i]));
console.log(c);
You would iterate through both arrays, doing the comparison at each step, and inserting the larger number:
Note: Even though you mention that you have equal length arrays, the two sample arrays you've given don't have the same length so my example uses similar equal-length arrays:
let a = [5, 2, 6, 2, 7]
let b = [2, 3, 7, 4, 3]
let c = [0, 0, 0, 0, 0]
// we can use a single loop index `i` since the arrays have same length
for (let i = 0; i < a.length; i++) {
// take the current number from a and from b
let numA = a[i]
let numB = b[i]
// determine larger of the two numbers
let largerNumber = numA > numB ? numA : numB
// add larger to array at current position
c[i] = largerNumber
}
console.log(c)
You can simplify your solution to be a simple map operation, as demonstrated by dhilt.
Just use a simple for loop:
var a = [2, 3, 7, 8];
var b = [3, 2, 5, 9];
var c = [0, 0, 0, 0];
for (var i = 0; i < c.length; i++) {
c[i] = a[i] > b[i] ? a[i] : b[i];
}
console.log("Result: "+c);
try this, below code takes two arrays and gives the result of max number
var array=[5,3,7,7,5];
var array2 = [5,6,4];
var array3=array.concat(array2);
var max=array3.sort((a,b)=>b-a)[0];
console.log("Result: " + max);
see example:
var a = [5,2,6,2,7,5];
var b = [2,3,7,4,3];
var c = [0,0,0,0,0];
for(var i in c){
c[i]=a[i]>b[i]?a[i]:b[i];
}
console.log('result:' + c);

Merge two of one dimensional array into two dimensional array javascript

I have n (but for now, let say just two) of one dimensional arrays like this image of my console :
And I want to merge these two arrays by the corresponding key and put it into two dimensional array :
The result is something like :
[["1 279 226,08" , "127"],[null , null],["-188 033,77", "154"],..... so on ......]
And the list of one dimensional array is dynamic, it could be more than 2 arrays.
So example if I have 3 arrays, then my two dimensional array would look like :
[ ["1 279 226,08" , "127" , "blabla"], [null , null , "blabla"], ["-188 033,77", "154", "blabla"], ..... so on ......]
Any ideas of implementing it would be appreciate.
You could transpose the array with a nested loop and switch the indices for assigning the values.
var array = [["1 279 226,08", null, "-188 033,77"], ["127", null, "154"], ["blabla", "blabla", "blabla"]],
result = array.reduce(function (r, a, i) {
a.forEach(function (b, j) {
r[j] = r[j] || [];
r[j][i] = b;
});
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Since all of your arrays have the same size, you can loop just on the lenght of the first array, i.e. a.
Then we pass to appendArrays the single value of a , b, ..., and we return the an array to push into merged
var a = ["123", null, "ciao"]
var b = ["321", 1, "pippo"]
var c = ["111", 5, "co"]
var merged = []
for (i = 0; i < a.length; i++) {
merged.push(appendArrays(a[i], b[i], c[i]));
}
console.log(merged);
function appendArrays() {
var temp = []
for (var i = 0; i < arguments.length; i++) {
temp.push(arguments[i]);
}
return temp;
}
This should do what you want.
var arr1 = [1, 2, 3, 4, 5, 6];
var arr2 = [6, 5, 4, 3, 2, 1];
var arr3 = [7, 8, 9, 10, 11, 5];
var arr4 = [12, 34, 55, 77, 22, 426];
var arrCollection = [arr1, arr2, arr3, arr4];
// if array sizes are variable.
// if not max = arrCollection[0].length will do
var max = Math.max.apply(Math, arrCollection.map(function(a) {
return a.length;
}));
var arrFinal = [];
for (let i = 0; i < max; i++) {
var arr = [];
arrCollection.forEach(function(a) {
arr.push(a[i]);
});
arrFinal.push(arr);
}
console.log(arrFinal);
You can create this with two forEach() loops.
var arr1 = [[1, 2], [3, 4], [5, 6]];
var arr2 = [[1, 2, 3], [4, 5, 6], [7, 8], [9, 10, 12, 14]];
let merge = function(arr) {
var result = [];
arr.forEach(function(e, i) {
e.forEach(function(a, j) {
if (!result[j]) result[j] = [a];
else result[j].push(a)
})
});
return result;
}
console.log(JSON.stringify(merge(arr1)))
console.log(JSON.stringify(merge(arr2)))

2D array into an object

Essentially, I would like to make:
var current = [
[4, 'socks'],
[2, 'pants'],
[1, 'shoes'],
[5, 'hats']
];
Into this:
var current = {
socks: 4,
pants: 2,
shoes: 1,
hats: 5
};
If you want to iterate through a collection and return a single object then reduce() is your tool:
var current = [
[4, 'socks'],
[2, 'pants'],
[1, 'shoes'],
[5, 'hats']];
current.reduce(
function(m,c) {
m[c[1]] = c[0];
return m;
}, {})
// Object {socks: 4, pants: 2, shoes: 1, hats: 5}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
You can loop through the arrays in the array and add them as properties in the object:
var result = {};
for (var i = 0; i < current.length; i++) {
result[current[i][1]] = current[i][0];
}
Demo:
var current = [
[4, 'socks'],
[2, 'pants'],
[1, 'shoes'],
[5, 'hats']];
var result = {};
for (var i = 0; i < current.length; i++) {
result[current[i][1]] = current[i][0];
}
// show result in snippet
document.write(JSON.stringify(result));
With [].forEach.call():
var current = [
[4, 'socks'],
[2, 'pants'],
[1, 'shoes'],
[5, 'hats']
];
var res = {};
[].forEach.call(current, function(el) {
res[el[1]] = el[0];
});
console.log(res);
var html = document.getElementById("result");
result.innerHTML = JSON.stringify(res);
<div id="result"></div>

Categories

Resources