Restructure the array to align with the corresponding elements in another

I am looking to filter an array based on ids from another array. Specifically, I have an array of tweet ids associated with a certain hashtag in the object I'm working with.

h.tweet_ids = [*someTweetID*, *someOtherTweetID*, …]

On the other hand, I also have a userTimeline array that includes all tweets sent by the user who is logged in.

The structure of the userTimeline array looks like this ():

[
 {
   "coordinates": null,
   "favorited": false,
   "truncated": false,
   "created_at": "Wed Aug 29 17:12:58 +0000 2012",
   "id_str": "240859602684612608",
   ...
 },
 {
   "coordinates": null,
   "favorited": false,
   "truncated": false,
   "created_at": "Sat Aug 25 17:26:51 +0000 2012",
   "id_str": "239413543487819778",
   ...
 }
]

My goal is to filter the userTimeline array to only retrieve tweets whose ids match the ones in h.tweet_ids.

So far, I've attempted using nested loops, but I've encountered issues with it sometimes going into an infinite loop...

$scope.showTweetsForHashtag = function(h){
  var userTimeline = $scope.userTimeline,
     tweetId=h.tweetId,
     hTweets = [];
  for (var i = 0; i < tweetId.length; i++) {
     for (var j = 0; j < userTimeline.length; j++) {
        if (userTimeline[j].id_str===tweetId[i]) {
           hTweets.push(userTimeline[j]);
        }
     }
  }
  $scope.selHash=h.Hashtag;
  $scope.hTweets=hTweets;
  if (!$scope.hModal) {
     $scope.hModal=true
  }
};

Thank you for your assistance!

Cheers ^Q

Answer №1

In my approach with lodash, I would write the following code:

var users = [
  {
    "coordinates": null,
    "favorited": false,
    "truncated": false,
    "created_at": "Wed Aug 29 17:12:58 +0000 2012",
    "id_str": "240859602684612608",
    "entities": {
    },
    "in_reply_to_user_id_str": null,
    "contributors": null,
    "text": "Introducing the Twitter Certified Products Program: https://t.co/MjJ8xAnT",
    "retweet_count": 121,
    "in_reply_to_status_id_str": null,
    "id": 240859602684612608,
    "geo": null,
    "retweeted": false,
    "possibly_sensitive": false,
    "in_reply_to_user_id": null,
    "place": null,
    "user": {
    },
    "in_reply_to_screen_name": null,
    "source": "",
    "in_reply_to_status_id": null
  },
  {
    "coordinates": null,
    "favorited": false,
    "truncated": false,
    "created_at": "Sat Aug 25 17:26:51 +0000 2012",
    "id_str": "239413543487819778",
    "entities": {
    },
    "in_reply_to_user_id_str": null,
    "contributors": null,
    "text": "We are working to resolve issues with application management & logging in to the dev portal: https://t.co/p5bOzH0k ^TS",
    "retweet_count": 105,
    "in_reply_to_status_id_str": null,
    "id": 239413543487819778,
    "geo": null,
    "retweeted": false,
    "possibly_sensitive": false,
    "in_reply_to_user_id": null,
    "place": null,
    "user": {
    },
    "in_reply_to_screen_name": null,
    "source": "",
    "in_reply_to_status_id": null
  }
];

var tweet_ids = ["240859602684612608", "000000"];
var matchIds = _.intersection(_.pluck(users, 'id_str'),tweet_ids );
var matchTweets = _.filter(users,function(userTmp){
  return matchIds.indexOf(userTmp.id_str) !== -1 ;
})

console.log(matchTweets);

$("body").append(JSON.stringify(matchTweets))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.min.js"></script>

<body></body>

Answer №2

Fortunately, I managed to find a solution without using Lodash!

$scope.showTweetsForHashtag = function(h) {
    var userTimeline = $scope.userTimeline,
        tweetId = h.tweetId,
        hTweets = [];
    if (Array.isArray(tweetId)) {
        for (var i = 0; i < tweetId.length; i++) {
            var hTweet = userTimeline.filter(function(el) {
                return el.id_str === tweetId[i];
            });
            hTweets = hTweets.concat(hTweet);
        }
        $scope.hTweets = hTweets;
    } else {
        $scope.hTweets = userTimeline.filter(function(el) {
            return el.id_str === tweetId;
        });
    }
    $scope.selHash = h.Hashtag;
    if (!$scope.hModal) {
        $scope.hModal = true
    }
};

Thank you for your assistance!

^Q

Answer №3

To achieve the desired result, utilize Array.prototype.filter just like in the example provided at http://jsfiddle.net/2LcpaeLm/:

var tweet_ids = [1,2,3,5,8,13,21];
var tweets = [{
    'id_str': 1
}, {
    'id_str': 4
}, {
    'id_str': 8
}, {
    'id_str': 11
}];

var filtered = tweets.filter(function (t) {
    for (var i = 0, len = tweet_ids.length; i < len; i++) {
        if (tweet_ids[i] == t.id_str)
            return true;
    }
});

console.log(filtered);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Filtering Images by Alt Attribute: A Comprehensive Guide

I'm working on an image gallery project that includes a search box feature. My goal is to dynamically hide images that do not have an alt attribute matching the user's search query. Despite several attempts, I keep encountering issues where all e ...

Activate video playback when scrolling, but ensure it only occurs one time

I've encountered an issue with my script that is meant to play a video when it reaches a certain position on scroll. The problem is, if the video is paused and scrolling continues, it starts playing again. I attempted to use just one scroll function b ...

Ways to Ensure a Property of an Object Remains Synced with Another

I'm dealing with the following Object structure: { a: "123" b: "$a" } In this setup, b should always be equal to the value of a. Any suggestions on how I can achieve this using JavaScript? ...

Choose an option to adjust the transparency of the image

I'm struggling with a select option and need some assistance. I have a select dropdown list where I want the image opacity to change from 0.3 to 1 when selected or onchange event occurs. The catch is, I can't use the value of the option because i ...

Delete any array elements in MongoDB that have an ID matching an element in the specified array

I am facing an issue with removing elements from an orders array in nodejs. I have a list of IDs obtained from a post request and I need to remove all elements from the orders array that match these IDs. For example, let's say we have remove_id = [&a ...

Attempting to utilize the ngSwitch directive within an Angular application

I have been experimenting with this code snippet in Angular, but unfortunately, it is not functioning as expected. As a newcomer to Angular, I am struggling to solve this issue. My objective is simply to display a specific element based on a step number ...

The locomotive scroll elements mysteriously vanish as you scroll, leaving the footer abruptly cut off

After successfully implementing locomotive scroll on my website, I encountered some issues when uploading it to a live server. Elements started bumping into each other causing flickering and disappearing, with the footer being cut off as well. It appears t ...

Troubleshooting: Issue with jQuery not recognizing this.id

Hey everyone, check out my code snippet below: $ (".input_check").change (function (){ if ($ (this).is (':checked')) { console.log(this.id + 'is checked') } else { console.log(this.id + &apo ...

Android Studio crashes unexpectedly while attempting to access data from an array

As I ponder over this particular query, I find myself unable to crack the code. Let's take a look at the snippet below: private void fetchJSONData() { AsyncHttpClient client = new AsyncHttpClient(); client.get("http://dev.vision-is.nl/klante ...

What is the best way to incorporate a JavaScript function into an Angular 2 template?

I need a slider for my project and I am using AdminLTE <input type="text" value="" class="slider form-control" data-slider-min="-200" data-slider-max="200" data-slider-step="5" data-slider-orientation="horizontal" data-slider-sele ...

Adjusting the dimensions of the central container

Does anyone have suggestions on how to resize the middle red container when the window is resized, considering the fixed-width black containers on the left and right? I am aware that this can be achieved using jQuery by calculating the window width and a ...

Navigating a secure Koa authentication flow using compose mechanism

I have this isAuthenticated function in expressjs that composes middleware into one. Now, I need to achieve the same functionality in Koa as I am migrating from Express. How can I replicate this in Koa? import compose from 'composable-middleware&apos ...

The vertical scroll position of a container with overflowing content does not correspond to the height of its elements

I have a div that has a fixed height of 155px and is set to scroll vertically when overflow occurs. Inside this div, there is an unordered list with a height of 338px. I am attempting to determine when a user reaches the bottom of that div. $('.myD ...

Error: Unable to render followers list due to incorrect data type

I have embarked on creating a unique Github user card generator that retrieves user data and their followers' information from the GitHub API, then displays them on a personalized user card. The follower's data received is in the form of an array ...

What is the best way to display several markers on a Google Map at once?

I am currently working on a functionality where I retrieve latitude and longitude from a JSON file and display markers on a Google map. However, my issue is that only one marker is appearing on the Google map, while the others are not showing up. Below i ...

Encountering the "ExpressionChangedAfterItHasBeenCheckedError" in Angular 2

As I try to fill in multiple rows within a table that I've created, the table gets populated successfully. However, an error message pops up: "ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous valu ...

Using Vue.js: Executing a method in one component from another

Currently working with Vue.Js version 2 and looking to achieve a functionality where I can call the method c1method from component1 within the method c2method in component2 in order to reload data post submission. Vue.component('component1', { ...

How to show the current week using React Native

Looking to show the current week of the month in a specific format using react-native: (Week 2: 05.10 - 11.10) (for example, displaying week 2 of the current month) Any ideas on how to make this happen? I'm aware of packages like momentjs that can ...

Is it feasible to have unique popups for individual textbox edits?

I am experiencing a problem with a popup in Asp.net while using AJAX modalpopup extender. I am wondering if it is feasible to display one type of popup when the user modifies certain textboxes, and another type of popup for the remaining textboxes. I beli ...

Prevent the transmission of keydown events from dat.GUI to the Three.js scene to maintain event isolation

This code snippet (below) contains 2 event listeners: renderer.domElement.addEventListener("pointerdown", changeColor, false); document.addEventListener("keydown", changeColor, false); Both of these event listeners trigger a color chan ...