简体   繁体   中英

Compare and sort array using javascript

For the following

array1 = [{
        "x": 0,
        "y": 1,
        "z": 1,
        "i": "chart1"
         }, {
        "x": 0,
        "y": 2,
        "z": 1,
        "i": "chart2"
         }, {
        "x": 1,
        "y": 1,
        "z": 1,
        "i": "chart3 "
    }
]

array2 = [{
        "x": 1,
        "y": 1,
        "z": 1,
        "i": "chart1"
        }, {
        "x": 0,
        "y": 1,
        "z": 1,
        "i": "chart2"
        }, {
        "x": 0,
        "y": 2,
        "z": 1,
        "i": "chart3"
    }
]

compare x and y of array1 and array2 and find the position if it is equal and return the set of array of i value.

ie in above case it should return:

array3=["chart2","chart3","chart1"]

I have a json as below:

json = [{
        "visType:" bar "," visName ":" chart1 "},{" visType: "bar",
        "visName": "chart2"
    }, {
        "visType:" Pie "," visName ":" chart3 "}]

And this need to be sort based on array3 = ["chart2","chart3","chart1"] the output should be as in updated json

updatedjson = [{
        "visType:" bar "," visName ":" chart2 "},{" visType: "Pie",
        "visName": "chart3"
    }, {
        "visType:" bar "," visName ":" chart1 "}]

I need a solution using lodash or javascript .

const array3 = [...array1, ...array2].filter(({x,y}) => x===y);
const updatedjson = array3.map(({i}) => json.find(({visName}) => i === visName));

Edit: Fixed the input data which was full of syntax errors:

var array1 = [{ "x": 0, "y": 1, "z": 1, "i": "chart1" }, { "x": 0, "y": 2, "z": 1, "i": "chart2" }, { "x": 1, "y": 1, "z": 1, "i": "chart3" }];
var array2 = [{ "x": 1, "y": 1, "z": 1, "i": "chart1" }, { "x": 0, "y": 1, "z": 1, "i": "chart2" }, { "x": 0, "y": 2, "z": 1, "i": "chart3" }];

var json = [
    { "visType": "bar", "visName": "chart1" },
    { "visType": "bar", "visName": "chart2" },
    { "visType": "Pie", "visName": "chart3" }
];

const array3 = [...array1, ...array2].filter(({ x, y }) => x === y);
const updatedjson = array3.map(({ i }) => json.find(({ visName }) => i === visName));
console.log(array3);
console.log(updatedjson);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM