-1

In angular 7 projects for a specific component I have to get data from wp site and dotnet site via api. From wp api I am getting data as(console log data ):

(2) [{…}, {…}]
0: {title: "Henk WJ Ovink", description: "Special Envoy for International Water Affairs, Kin…ands, and Sherpa to the High Level Panel on Water", slug: "http://siwidev.websearchpro.net/press/", image: "http://siwidev.websearchpro.net/wp-content/uploads/2019/03/636385501414087698.png", imageWidth: 1903, …}
1: {title: "Amina J. Mohammed", description: "Deputy Secretary-General United Nations", slug: "http://siwidev.websearchpro.net/community/", image: "http://siwidev.websearchpro.net/wp-content/uploads/2019/03/h20fddcc.jpg", imageWidth: 776, …}
length: 2
__proto__: Array(0)

From dotnet api I am getting data as(console log data):

(5) [{…}, {…}, {…}, {…}, {…}]
0: {id: 8342, title: "Panaceas or painkillers – what role for sustainability assessment tools?", description: null, slug: "8342-panaceas-or-painkillers---what-role-for-sustainability-assessment-tools", image: "https://siwi.websearchpro.net/Content/ProposalReso…g-2019-8342-tn-img-2019-8605-iStock-500553193.jpg", …}
1: {id: 8380, title: "Inclusive Policy and Governance for Water and Sanitation ", description: null, slug: "8380-inclusive-policy-and-governance-for-water-and-sanitation", image: "https://siwi.websearchpro.net/Content/ProposalReso…019-8420-img-2019-8420-org-InkedPhoto IWRM_LI.jpg", …}
2: {id: 8464, title: "Cities4Forests: 50 cities commit to forests citing water benefits", description: null, slug: "8464-cities4forests-50-cities-commit-to-forests-citing-water-benefits", image: "https://siwi.websearchpro.net/Content/ProposalReso…464-tn-img-2019-8481-WESCA illegal FS dumping.jpg", …}
3: {id: 8474, title: "Urban water resiliency: a coordinated response from source to settlement ", description: null, slug: "8474-urban-water-resiliency-a-coordinated-response-from-source-to-settlement", image: "https://siwi.websearchpro.net/Content/ProposalResources/Image/Default/default-www-tn.jpg", …}
4: {id: 8526, title: "Including all: participatory approaches in water governance and programmes ", description: null, slug: "8526-including-all-participatory-approaches-in-water-governance-and-programmes", image: "https://siwi.websearchpro.net/Content/ProposalReso…ge/2019/Thumbnail/img-2019-8526-tn-Field trip.JPG", …}
length: 5
__proto__: Array(0)

Now I need to merge these 2 array, shuffle the array element and show it. What I have done so far:

public merge_array : Array<{ }> = [];
/* wp api */
this.accountService.getKeynote( wp_params ).then( ( response: any ) => {
    this.merge_array ? this.merge_array : [];
    this.wp_data_array = response.data;
    for ( let value of this.wp_data_array ) {
        this.merge_array.push( value );
    };
});
/* dot net api */
this.accountService.getConferences( params ).then( ( dotnetresponse: any ) => {
    if ( dotnetresponse.status == 'Ok' ) {
        this.merge_array ? this.merge_array : [];
        this.dotnet_data_array = dotnetresponse.conferences;
        for ( let value of this.dotnet_data_array ) {
            this.merge_array.push( value );
        };
    }
});

But when I console log 'merge_array' here the result is:

[]
0: {title: "Henk WJ Ovink", description: "Special Envoy for International Water Affairs, Kin…ands, and Sherpa to the High Level Panel on Water", slug: "http://siwidev.websearchpro.net/press/", image: "http://siwidev.websearchpro.net/wp-content/uploads/2019/03/636385501414087698.png", imageWidth: 1903, …}
1: {title: "Amina J. Mohammed", description: "Deputy Secretary-General United Nations", slug: "http://siwidev.websearchpro.net/community/", image: "http://siwidev.websearchpro.net/wp-content/uploads/2019/03/h20fddcc.jpg", imageWidth: 776, …}
2: {id: 8342, title: "Panaceas or painkillers – what role for sustainability assessment tools?", description: null, slug: "8342-panaceas-or-painkillers---what-role-for-sustainability-assessment-tools", image: "https://siwi.websearchpro.net/Content/ProposalReso…g-2019-8342-tn-img-2019-8605-iStock-500553193.jpg", …}
3: {id: 8380, title: "Inclusive Policy and Governance for Water and Sanitation ", description: null, slug: "8380-inclusive-policy-and-governance-for-water-and-sanitation", image: "https://siwi.websearchpro.net/Content/ProposalReso…019-8420-img-2019-8420-org-InkedPhoto IWRM_LI.jpg", …}
4: {id: 8464, title: "Cities4Forests: 50 cities commit to forests citing water benefits", description: null, slug: "8464-cities4forests-50-cities-commit-to-forests-citing-water-benefits", image: "https://siwi.websearchpro.net/Content/ProposalReso…464-tn-img-2019-8481-WESCA illegal FS dumping.jpg", …}
5: {id: 8474, title: "Urban water resiliency: a coordinated response from source to settlement ", description: null, slug: "8474-urban-water-resiliency-a-coordinated-response-from-source-to-settlement", image: "https://siwi.websearchpro.net/Content/ProposalResources/Image/Default/default-www-tn.jpg", …}
6: {id: 8526, title: "Including all: participatory approaches in water governance and programmes ", description: null, slug: "8526-including-all-participatory-approaches-in-water-governance-and-programmes", image: "https://siwi.websearchpro.net/Content/ProposalReso…ge/2019/Thumbnail/img-2019-8526-tn-Field trip.JPG", …}
length: 7
__proto__: Array(0)

The length of merge array is coming as 0. I am not able to solve this. What am I doing wrong regarding array initialization or array push. Any help/suggestions are welcome.

samjhana joshi
  • 1,995
  • 4
  • 35
  • 69
  • `length: 7` - why conclude it's zero? `Array(0)` is the *prototype*. – jonrsharpe May 12 '19 at 06:48
  • @jonrsharpe I did console.log(this.merge_array.length) and it's giving me 0 thought there are data. I am needing the array length but I am always getting 0 no matter what ? – samjhana joshi May 12 '19 at 06:49
  • Are you? Because in the output you've posted we can see it says 7. – jonrsharpe May 12 '19 at 07:04
  • @jonrsharpe Yes it does show but when i console the length(console.log(this.merge_array.length)) it is showing 0 always. I can't seem to get exact length except 0. – samjhana joshi May 12 '19 at 07:08

2 Answers2

0

Simple Object.assign(target, source) should do the trick

Documentation at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

To shuffle the array, use destructuring:

for (let i = target.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [target[i], target[j]] = [target[j], target[i]];
}
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Saksham
  • 9,037
  • 7
  • 45
  • 73
0

It is no surprise that the array will be empty, because the returning of Promises operates asynchronously. Hence, both arrays will be empty at the point when you log the values.

What you need to do is to use Promise.all. According to the documentation,

The Promise.all() method returns a single Promise that resolves when all of the promises passed as an iterable have resolved or when the iterable contains no promises. It rejects with the reason of the first promise that rejects.

What can do now, is to use Promise.all to resolve the promises from both requests (you can use console.log(response) to verify that the promises are indeed resolved and a value is returned), followed by using the spread syntax to merge both arrays. Then we will randomly reshuffle the array using the algorithm provided over here by Laurens Holst. This should give you the resulting shuffled array.

const getKeynote = this.accountService.getKeynote(wp_params);
const getConferences = this.accountService.getConferences(params);

Promise.all([getKeynote, getConferences]).then(response => {
  //console.log(response);
  const merged = [...response[0], ...response[1]];
  const shuffleArray = (array) => {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
  };
  shuffleArray(merged);
  console.log(merged);
});
wentjun
  • 40,384
  • 10
  • 95
  • 107