1

I have two arrays of objects in js those looks like this:

Array1
   0:Object
      name: "name1"
      value:7
   1:Object
      name: "name2"
      value:5
   2:Object
      name: "name3"
      value:6

Array2
   0:Object
      name: "name1"
      value:3
   1:Object
      name: "name2"
      value:4
   2:Object
      name: "name3"
      value:8

I'd like to create a third array which will contain results from multiplication values from array1 and array2 (doesn't need to be an objects array - could contain only int values). This mean:

Array1        Array2        Array3
value:7  *    value:3   =   value:21
value:5  *    value:4   =   value:20
value:6  *    value:8   =   value:48

Do you know an easy and good way to create this third table with values like above and display it on website? Thanks in advance :)

5 Answers 5

1

Pure javascript, no jQuery needed:

function addArrays(arr1, arr2, prop) {
  var func = function(curr) {
    return curr[prop];
  }
  var arr1v = arr1.map(func), arr2v = arr2.map(func), output = [];
  arr1v.forEach(function(curr, i){
    output[i] = arr1v[i] * arr2v[i];
  });
  return output;
}
addArrays([{value:7},{value:5},{value:6}],[{value:3},{value:4},{value:8}],"value") //->[21, 20, 48]

Sign up to request clarification or add additional context in comments.

Comments

1

Really ,i am wondered why there are a complicated answers here ,while , Javascript is a functional programming language :

Just one line :

array3= array1.map(function(e,i){return {value : (e.value * array2[i].value)}; }) ; 

Fiddle

Comments

0

Try this

var ar3 = [];
for(var i = 0; i <= array1.length; i++){
    var valu = array1[i].value * array2[i].value;
    ar3[i] = valu;
}

Comments

0

You can use the power of LINQ to join the two result sets and select a third column as the result of the multiplication of the two source columns. (Just like you would do in SQL)

The JavaScript implementation of LINQ can come in quite handy here. Check out LinqJS:

http://linqjs.codeplex.com/

Here's a good article on it http://www.codeproject.com/Articles/603742/LINQ-for-JavaScript

$Linq also looks promising https://jscriptlinq.codeplex.com/

4 Comments

The question is about simple line-by-line multiplication of arrays, rather than about SQL's cartesian product of two arrays.
Here is the sample of SQL's product of two arrays: jsfiddle.net/3trpj4nw/3 It gives 9 (3 by 3) elements array instead 3, but there is no key for JOIN operation.
I completely mis-interpreted the question - my bad sorry :)
Mea culpa! I missed "name" key field in the question. I just posted another answer with pure JS and SQL answers. And, definitly, it can be done with LINQ library. Sorry, again!
0

You can do it in multiple ways:

Option 1: Pure JavaScript nested loops You can do it with pure JavaScript just with two nested loops. It is relatively slow on big arrays, but quite simple.

Option 2: Pure JavaScript loop with preindexation You can do it preindex one of arrays to fast access to it.

Option 3: Using special library As an alternative you can use special SQL or LINQ (as mentioned in the other answer) libraries, e.g. Alasql, where the library automatically creates index on the second array to faster access to avoid unnecessary loops.

Performance: You can compare the speed of all three variants on joining 10000 x 10000 arrays (simple nested loops and with preindexation) in this jsPerf test. Option 2 is fastest.

See the working snippet below with all three options or play with it in jsFiddle.

(Disclaimer: I am an author of Alasql)

var Array1 = [{name:'name1',value:7},{name:'name2',value:5},{name:'name3',value:6}];
var Array2 = [{name:'name1',value:3},{name:'name2',value:4},{name:'name3',value:8}];

// 1. Pure JavaScript option with nested loops
var Array3 = [];
for(var i=0;i<Array1.length;i++) {
    for(var j=0;j<Array2.length;j++) {
        if(Array1[i].name == Array2[j].name) {
            Array3.push({value:Array1[i].value * Array2[i].value});
            break;
        }
    }
}

document.getElementById("res1").textContent = JSON.stringify(Array3);

// 2. Preindexation version
var idx = {};
for(var j=0;j<Array2.length;j++) {
   idx[Array2[j].name] = Array2[j].value;
}
var Array3 = [];
for(var i=0;i<Array1.length;i++) {
    Array3.push({value:Array1[i].value * idx[Array1[i].name]});
}

document.getElementById("res2").textContent = JSON.stringify(Array3);

// 3. SQL library option
var Array3 = alasql('SELECT Array1.[value]*Array2.[value] AS [value] \
                   FROM ? Array1 JOIN ? Array2 USING name',[Array1, Array2]);

document.getElementById("res3").textContent = JSON.stringify(Array3);
<script src="http://alasql.org/console/alasql.min.js"></script>
<p>Pure JavaScript nested loops: </p><div id="res1"></div>
<p>Pure JavaScript preindexation: </p><div id="res2"></div>
<p>Alasql version: </p><div id="res3"></div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.